package com.xoa.service.im;

import cn.jiguang.common.ClientConfig;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosAlert;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.huawei.push.javasdk.exception.HuaweiMesssagingException;
import com.huawei.push.javasdk.message.AndroidConfig;
import com.huawei.push.javasdk.message.BadgeNotification;
import com.huawei.push.javasdk.message.ClickAction;
import com.huawei.push.javasdk.messaging.*;
import com.tencent.xinge.*;
import com.xoa.controller.im.Model.*;
import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.enclosure.AttachmentMapper;
import com.xoa.dao.im.ImChatDataMapper;
import com.xoa.dao.im.ImMessageMapper;
import com.xoa.dao.im.ImRoomMapper;
import com.xoa.dao.users.UserPrivMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.common.SysPara;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.im.ImChatData;
import com.xoa.model.im.ImMessage;
import com.xoa.model.im.ImRoom;
import com.xoa.model.users.SimpleUser;
import com.xoa.model.users.UserPriv;
import com.xoa.model.users.Users;
import com.xoa.service.sms.impl.SmsServiceImpl;
import com.xoa.service.users.UsersService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.FileUploadUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.CheckCallBack;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.ipUtil.MachineCode;
import com.xoa.util.page.PageParams;
import org.apache.commons.io.IOUtils;
import org.igniterealtime.restclient.RestApiClient;
import org.igniterealtime.restclient.entity.AuthenticationToken;
import org.igniterealtime.restclient.entity.MUCRoomEntity;
import org.json.JSONObject;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.ws.rs.core.Response;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * @作者 韩东堂
 * @创建日期 2017-4-24 下午3:43:10
 * @类介绍 Im数据信息服务类
 * @构造参数 无
 */
@Service
public class ImChatDataService {
    private final String one = "1";
    @Resource
    ImMessageMapper messageDao;
    @Resource
    ImChatDataMapper chatDataDao;
    @Resource
    ImRoomMapper roomDao;
    @Resource
    ImEnclosureService attachService;
    @Resource
    AttachmentMapper attachmentMapper;
    @Resource
    UsersService usersService;
    @Resource
    SysParaMapper sysParaMapper;
    @Resource
    UsersMapper usersMapper;
    @Resource
    UserPrivMapper userPrivMapper;

    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Value("${xg_push_msg_android_key}")
    String androidKey;
    @Value("${xg_push_msg_android_sercetkey}")
    String androidSercetKey;
    @Value("${xg_push_msg_ios_key}")
    String iosKey;
    @Value("${xg_push_msg_ios_sercetkey}")
    String iosSercetKey;

    @Value("${xg_push_msg_ios_store_key}")
    String iosStopKey;
    @Value("${xg_push_msg_ios_store_sercetkey}")
    String iosStopSercetKey;


    @Value("${j_push_msg_key}")
    String JGKey;
    @Value("${j_push_msg_sercetkey}")
    String JGSercetKey;

    @Value("${j_push_msg_ios_store_key}")
    String  JGIosStoreKey;
    @Value("${j_push_msg_ios_store_sercetkey}")
    String JGIosStoreSercetKey;


    @Value("${openfire_host}")
    String openfireHost;
    @Value("${openfire_port}")
    String openfirePort;
    @Value("${openfire_default_description}")
    String openfireDefaultDescription;
    @Value("${openfire_auth_token}")
    String openfireAuthToken;

    @Value("${App_Id_Huawei_Key}")
    String AppIdKey;
    @Value("${SecretKey}")
    String SecretKey;
    @Value("${Huawei_badge_class}")
    String Huawei_badge_class;


    //用户在华为开发者联盟申请的appId和appSecret（会员中心->应用管理，点击应用名称的链接）
    private static String appSecret = "1ef4fa0d6b7cc6b06f4153579b478856";
    private static  String appId = "100221479";

    /**获取认证Token的URL*/
    private static  String tokenUrl = "https://login.cloud.huawei.com/oauth2/v2/token";
    /**应用级消息下发API*/
    private static  String apiUrl = "https://api.push.hicloud.com/pushsend.do";
    private static  String accessToken;//下发通知消息的认证Token
    private static  long tokenExpiredTime;  //accessToken的过期时间
    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-5-23 下午4:55:08
     * 方法介绍:   存一条信息包括附件
     * 参数说明:   @param request
     * 参数说明:   @param flag
     * 参数说明:   @param from_uid
     * 参数说明:   @param to_uid
     * 参数说明:   @param of_from
     * 参数说明:   @param of_to
     * 参数说明:   @param content
     * 参数说明:   @param type
     * 参数说明:   @param time
     * 参数说明:   @param uuid
     * 参数说明:   @param msg_type
     * 参数说明:   @param voice_time
     * 参数说明:   @return
     *
     * @return Object
     */
    @Transactional(readOnly = false)
    public Object putMessageInfo(MultipartFile file, HttpServletRequest request, final Integer flag, String from_uid,
                                 final String to_uid, String of_from, String of_to, final String content,
                                 final String type, String time, String uuid, final String msg_type, String voice_time, Long atime) {
        Status s = new Status();
        final Files file1 = new Files();
        //全局变量记录在一个聊天中的最后一条信息 然后保存到imchatData表中如果存在则修改
        String fileID = "";
        String attachName = "";
        String lastThumbnailUrl = "";
        String lastTeeurlUrl = "";
        //全局变量记录在一个聊天中的最后一条信息
        try {
            String checkResult = StringUtils.checkNullUtils(
                    new CheckCallBack() {
                        @Override
                        public boolean isNull(Object obj) {
                            // TODO Auto-generated method stub
                            if (obj instanceof String) {
                                String a = (String) obj;
                                if (a == null || "".equals(a)
                                        || a.length() == 0)
                                    return true;
                            }
                            if (obj instanceof Integer) {
                                Integer a = (Integer) obj;
                                if (a == null)
                                    return true;
                            }
                            return false;
                        }
                    }, flag, "flag不能为空", from_uid, "from_uid不能为空", to_uid,
                    "to_uid不能为空", of_from, "of_from不能为空", of_to, "of_to不能为空",
                    type, "type不能为空");
            if (checkResult != null) {
                s.setStatus("error");
                return s;
            }
            final List<Users> users = new ArrayList<Users>();
            if ("0".equals(msg_type)) {//单聊
                Users user = usersService.getByUid(Integer.parseInt(to_uid));
                if (user == null || user.getUid() == null) {
                    s.setStatus("nopeople");
                    return s;
                }
                Map<String, Object> paramss = new HashMap<String, Object>();
                paramss.put("fromUid", from_uid);
                paramss.put("toUid", to_uid);

                List<String> msgFrees = chatDataDao.getMsgFreeByUid(paramss);

                if (msgFrees != null && msgFrees.size() > 0) {
                    String msgFree = msgFrees.get(0);
                    String[] tempUids = msgFree.split(",");
                    if (tempUids != null && tempUids.length > 0) {
                        int count = 0;
                        for (String toUiddd : tempUids) {
                            if (to_uid.equals(toUiddd)) {
                                count++;
                                break;
                            }
                        }
                        if (count == 0) {
                            users.add(user);
                        }
                    }
                } else {
//                    System.out.println("0==||===========>消息打扰");
                    users.add(user);
                }

            } else {  //群聊
                Map<String, String> map = new HashMap<String, String>();
                map.put("roomOf", to_uid);
                ImRoom room = roomDao.getRoomByRoomOf(map);
                //排除群聊中设置免打扰的人员
                ImChatData imChatData = chatDataDao.getGroupByToUid(to_uid);
                List<Users> tempUser = new ArrayList<Users>();
                if (imChatData != null && !StringUtils.checkNull(imChatData.getMsg_free())) {
                    String[] tempUids = imChatData.getMsg_free().split(",");
                    tempUser = usersMapper.getUsersByUids(tempUids);
                }
                if (!StringUtils.checkNull(room.getRmemberUid())) {
                    String[] uids = room.getRmemberUid().split(",");
                    List<Users> userss = usersMapper.getUsersByUids(uids);
                    if (tempUser.size() > 0) {
                        for (Users u1 : userss) {
                            int count = 0;
                            for (Users u2 : tempUser) {
                                if (u1.getUid().equals(u2.getUid())) {
                                    count++;
                                    break;
                                }
                            }
                            if (count == 0) {
                                users.add(u1);
                            }
                        }
                    } else {
                        users.addAll(userss);
                    }

                } else {
                    s.setStatus("nopeople");
                    return s;
                }
            }
            ImMessage record = new ImMessage();
            record.setFromUid(from_uid);
            record.setType(type);
            record.setOfTo(of_to);
            record.setOfFrom(of_from);
            record.setToUid(to_uid);
            record.setUuid(uuid);
            //text   voice     img  file
            Attachment attach = null;
            switch (flag) {
                case 1:
                    record.setContent(content);
                    break;
                case 3:
                    attach = attachService.upload(file, type, "im", "xoa" + (String) request.getSession().getAttribute(
                            "loginDateSouse"), true);
                    if (attach == null) {
                        s.setStatus("error");
                        return s;
                    }
                    record.setFileId(String.valueOf(attach.getAid()));
                    record.setFileName(attach.getYm());
                    //附件id
                    fileID = String.valueOf(attach.getAid());
                    //上传以后返回值交给ym
                    attachName = attach.getYm();
                    String fileString = attach.getUrl();
                    String path = attach.getPath();
                    //图片处理
                    if ("img".equals(type)) {
                        File picture = new File(fileString);
                        String deskFileName = UUID.randomUUID().toString() + ".png";
                        String deskUlr = path + System.getProperty("file.separator") + deskFileName;
                        FileUploadUtil.saveMinPhoto(fileString, deskUlr, 300, 1.0d);
                        File thmpicture = new File(deskUlr);
                        if (thmpicture.exists()) {
                            FileInputStream thmfis = new FileInputStream(thmpicture);
                            MultipartFile multipartFile = new MockMultipartFile(deskFileName, deskFileName, "img/txt", thmfis);
                            Attachment attachss = attachService.upload(multipartFile, type, "im", "xoa" + (String) request.getSession().getAttribute(
                                    "loginDateSouse"), true);
                            if (attachss != null) {
                                file1.setThumbnail_url(attachss.getAttUrl());
                                record.setThumbnailUrl(attachss.getAttUrl());
                                File thmpicture11 = new File(attachss.getUrl());
                                if (thmpicture11.exists()) {
                                    FileInputStream thmfiss = new FileInputStream(thmpicture11);
                                    BufferedImage thmsourceImgs = ImageIO.read(thmfiss);
                                    file1.setThumbnail_width(String.valueOf(thmsourceImgs.getHeight()));
                                    file1.setThumbnail_height(String.valueOf(thmsourceImgs.getWidth()));
                                }
                            }
                            thmfis.close();
                        }
                        FileInputStream fis = new FileInputStream(picture);
                        //获取图片大小
                        long size = fis.getChannel().size();
                        BufferedImage sourceImg = ImageIO.read(fis);
                        //返回值file
                        file1.setFile_name(attach.getAttachName());
                        file1.setFile_url(attach.getAttUrl());
                        file1.setFile_size(FormetFileSize(size));
                        file1.setFile_width(String.valueOf(sourceImg.getWidth()));
                        file1.setFile_height(String.valueOf(sourceImg.getHeight()));
                        fis.close();
                        //将附件信息保存起来
                        lastThumbnailUrl = attach.getAttUrl();
                        record.setRealUrl(attach.getAttUrl());
                    }
                    //voice   上传一条声音信息
                    if ("voice".equals(type)) {
                        //返回值file
                        file1.setFile_url(attach.getAttUrl());
                        file1.setVoice_time(voice_time);
                        //将附件信息保存起来
                        //将声音时间长度放入ThumbnailUrl 和 lastThumbnailUrl 用于记录时长  在app端处理  在获取时长返回时长时直接获取 可减缓服务器端压力
                        record.setThumbnailUrl(voice_time);
                        lastThumbnailUrl = voice_time;
                    }
                    //file 上传一个文档信息
                    if ("file".equals(type)) {
                        File picture = new File(fileString);
                        FileInputStream fis = new FileInputStream(picture);
                        long size = fis.getChannel().size();
                        file1.setFile_size(FormetFileSize(size));
                        file1.setFile_url(attach.getAttUrl());
                        file1.setFile_name(attach.getAttachName());
                        file1.setFile_type(attach.getAttachName().substring(attach.getAttachName().lastIndexOf(".") + 1));
                        record.setThumbnailUrl(attach.getAttUrl());
                        //将附件信息保存起来
                    }
                    break;
                default:
                    break;
            }
            record.setStime(String.valueOf(new Date().getTime()/1000));
            record.setMsgType(msg_type);
            if (atime == null) {
                atime = new Date().getTime();
            }

            record.setAtime(String.valueOf(atime));
            int meResult = messageDao.save(record);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("fromUid", from_uid);
            map.put("toUid", to_uid);

            ImChatData chatModel = new ImChatData();
            chatModel.setFromUid(from_uid);
            chatModel.setToUid(to_uid);
            chatModel.setOfFrom(of_from);
            chatModel.setOfTo(of_to);
            chatModel.setLastTime(String.valueOf(new Date().getTime()/1000));
            chatModel.setLastAtime(String.valueOf(atime));
            if ("img".equals(type)) {
                //反之将内容置为空值
                chatModel.setLastContent("[图片]");

                chatModel.setLastFileId(fileID);
                chatModel.setLastFileName(attachName);
                chatModel.setLastThumbnailUrl(lastThumbnailUrl);
            } else if ("voice".equals(type)) {
                //反之将内容置为空值
                chatModel.setLastContent("[语音]");

                chatModel.setLastFileId(fileID);
                chatModel.setLastFileName(attachName);
                chatModel.setLastThumbnailUrl(lastThumbnailUrl);
            } else if ("file".equals(type)) {
                //反之将内容置为空值
                chatModel.setLastContent("[文件]");

                chatModel.setLastFileId(fileID);
                chatModel.setLastFileName(attachName);
                chatModel.setLastThumbnailUrl(lastThumbnailUrl);
            } else {
                chatModel.setLastContent(content);
                //如果最后一条信息为文字    上一条信息为附件 则将其他字段改为空值  在声明时已经初始化为空值
                chatModel.setLastFileId(fileID);
                chatModel.setLastFileName(attachName);
                chatModel.setLastThumbnailUrl(lastThumbnailUrl);
            }
            chatModel.setType(type);
            chatModel.setUuid(uuid);
            chatModel.setMsgType(msg_type);
            int chResult = 0;
            if ("1".equals(msg_type)) {//群聊，如果是往一个群里发送消息，存在这个群的记录，就进行更新，否则添加
                String listId = chatDataDao.getDatagroupObject(chatModel.getToUid());
                if (StringUtils.checkNull(listId)) {
                    chatModel.setUidIgnore("");
                    chResult = chatDataDao.saveChat(chatModel);
                } else {
                    chatModel.setListId(listId);
                    chatModel.setUidIgnore("");
                    chResult = chatDataDao.updateChatlist(chatModel);
                }
            } else {//单聊，只要存在两个人的对话直接进行更新，否则，进行插入
                int i = chatDataDao.getCountSingleObject(map);
                if (i == 0) {
                    chatModel.setUidIgnore("");
                    chResult = chatDataDao.saveChat(chatModel);
                } else {
                    List<String> listId = chatDataDao.getDataSingleObject(map);
                    chatModel.setListId(listId.get(0));
                    chatModel.setUidIgnore("");
                    chResult = chatDataDao.updateChatlist(chatModel);
                }
            }


            final String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
            final String jixiema =this.getMachineCode12();
            final Attachment finalAttach = attach;
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            final Users users1 = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
            this.threadPoolTaskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        String userName = users1.getUserName();
                        String con = users1.getUserName() + ":" + content;
                        if (!"0".equals(msg_type)) {
                            Map<String, Object> paramMap = new HashMap<String, Object>();
                            paramMap.put("uid", users1.getUid());
                            paramMap.put("roomOf", to_uid);
                            ImRoom room = roomDao.selRoomByRoomOfUid(paramMap);
                            if (room != null) {
                                userName = room.getRnamr();
                            }
                        }

                        if (flag == 3) {//文件 图片 定位
                            //String confile = "";
                            if ("img".equals(type)) {
                                con = users1.getUserName() + ":[图片]";
                            } else {
                                con = users1.getUserName() + ":[" + finalAttach.getAttachName() + "]";
                            }
                        }

                        //目标设备Token集合
                        com.alibaba.fastjson.JSONArray  deviceTokens = new com.alibaba.fastjson.JSONArray();
                        List<String> tokens = new ArrayList<String>();
                        //极光推送list
                        List<String> jgList = new ArrayList<>();
                        for (int ssi = 0; ssi < users.size(); ssi++) {
                            //获取推送人的icqNo，即pushtoken
                            Users userAll = usersMapper.selectUserByUserId(users.get(ssi).getByname());
                            String token = userAll.getIcqNo();
                            if (StringUtils.checkNull(token)) {
                                String account = jixiema + users.get(ssi).getUserId() + sqlType;
                                jgList.add(account);
                            }else {
                                tokens.add(token);
                                deviceTokens.add(token);
                                testNotificationMessageSend(token, userName, con,1);
                            }
//                            String account = jixiema + users.get(ssi).getUserId() + sqlType;
//                            acc[ssi] = account;
                        }

                        //华为推送
                        if (tokens.size()>0){
                            if (StringUtils.checkNull(AppIdKey) && StringUtils.checkNull(SecretKey)) {
                                sendPushMessage(userName, con, deviceTokens);
                            }
                        }

                        if (jgList!=null && jgList.size()>0) {
                            //极光推送数组(适配推送结构)
                            String[] jgArray = jgList.toArray(new String[jgList.size()]);

                            //极光推送通用版（ios+andriod）
                            JPushClient jpushClient = new JPushClient(JGSercetKey, JGKey, null, ClientConfig.getInstance());
                            PushPayload payload = buildPushObject_all_alias_alert(jgArray, userName, con);
                            PushResult result = jpushClient.sendPush(payload);

                        PushResult resultIos = null;
                        if (!JGKey.equals(JGIosStoreKey)) {
                            //极光推送ios商店版
                            JPushClient jpushClientios = new JPushClient(JGIosStoreSercetKey, JGIosStoreKey, null, ClientConfig.getInstance());
                            PushPayload payloadIos = buildPushObject_ios(jgArray, userName, con);
                            resultIos = jpushClientios.sendPush(payloadIos);
                        }
                        }

                    /*    if (!"200".equals(result.getResponseCode()) && !"200".equals(resultIos.getResponseCode())) {
                            //信鸽推送
                            Message mess = new Message();
                            MessageIOS messageIOS = new MessageIOS();
                            ClickAction clickAction = new ClickAction();
                            JSONObject contentTest = new JSONObject();
                            JSONObject obj = new JSONObject();
                            JSONObject aps = new JSONObject();
                            clickAction.setActionType(ClickAction.TYPE_ACTIVITY);
                            clickAction.setActivity("123");
                            Style style = new Style(0, 1, 1, 1, 0, 1, 0, 1);

                            mess.setType(Message.TYPE_NOTIFICATION);
                            mess.setStyle(style);
                            mess.setTitle(userName);
                            mess.setContent(con);
                            mess.setAction(clickAction);

                            contentTest.put("title", userName);//标题
                            contentTest.put("body", con);//内容
                            aps.put("badge_type", 1);
                            aps.put("alert", contentTest);
                            aps.put("sound", "beep.wav");
                            obj.put("aps", aps);
                            messageIOS.setRaw(obj.toString());

                            XingeApp pushIos = new XingeApp(Long.parseLong(iosKey), iosSercetKey);//IOS
                            XingeApp pushStore = new XingeApp(Long.parseLong(iosStopKey), iosStopSercetKey);//ios商业版
                            XingeApp pushAndroid = new XingeApp(Long.parseLong(androidKey), androidSercetKey);//安卓

                            for (Users user : users) {
                                if (!users1.getUserId().equals(user.getUserId())) {
                                    String account = jixiema + user.getUserId() + sqlType;

                                    JSONObject ret = pushAndroid.pushSingleAccount(0, account, mess);
                                    JSONObject ret3 = pushIos.pushSingleAccount(0, account, messageIOS, XingeApp.IOSENV_PROD);
                                    JSONObject ret4 = pushStore.pushSingleAccount(0, account, messageIOS, XingeApp.IOSENV_PROD);
                                }
                            }
                        }*/
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            if (chResult == 1 && meResult == 1) {
                s.setStatus("IMok");
            } else {
                s.setStatus("IMerror");
            }
            if (flag == 3) {
                file1.setStatus("ok");
                if ("0".equals(msg_type)) {
                    file1.setUserId(to_uid);
                } else {
                    file1.setRoomId(to_uid);
                }

                return file1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            s.setStatus("IMerror");
        }
        return s;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-5-23 下午4:56:29
     * 方法介绍:   取得信息列表
     * 参数说明:   @param request
     * 参数说明:   @param ofFrom
     * 参数说明:   @return
     * 参数说明:   @throws FileNotFoundException
     * 参数说明:   @throws IOException
     * 参数说明:   @throws LineUnavailableException
     * 参数说明:   @throws UnsupportedAudioFileException
     *
     * @return List<ImMessageModel>
     */
    @Transactional(readOnly = false)
    public List<ImMessageModel> getImChatList(HttpServletRequest request, String ofFrom) throws FileNotFoundException, IOException, LineUnavailableException, UnsupportedAudioFileException {
        List<Object> datas = null;
        //读取配置文件
        String company = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        //String name = rb.getString("mysql.driverClassName");
        String osName = System.getProperty("os.name");
        StringBuffer sb = new StringBuffer();
        StringBuffer buffer = new StringBuffer();
        if (osName.toLowerCase().startsWith("win")) {
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if (uploadPath.indexOf(":") == -1) {
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if (basePath.indexOf("/xoa") != -1) {
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2 = basePath.substring(0, index);
                }
                sb = sb.append(str2 + "/xoa");
            }
            sb.append(uploadPath);
            buffer = buffer.append(rb.getString("upload.win"));
        } else {
            sb = sb.append(rb.getString("upload.linux"));
            buffer = buffer.append(rb.getString("upload.linux"));
        }


        List<Object> list = new ArrayList<Object>();
        list.add(ofFrom);
        //findByObject("from ImChatData where ofFrom=?", list)
        Map<String, Object> map = new HashMap<String, Object>();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        map.put("ofFrom", ofFrom);
        map.put("uid", user.getUid());
        datas = chatDataDao.getChatListByFrom(map);
        List<Object> icm = new ArrayList<Object>();
        List<ImMessageModel> iclmList = new ArrayList<ImMessageModel>();
        //迭代器遍历删除list元素
        Iterator<Object> it = datas.iterator();
        while (it.hasNext()) {
            ImChatData icmSingle = (ImChatData) it.next();
            List<ImMessage> imlist = new ArrayList<ImMessage>();
            if (icmSingle.getMsgType().equals("1")) {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("uid", user.getUid());
                paramMap.put("roomOf", icmSingle.getToUid());
                ImRoom room = roomDao.selRoomByRoomOfUid(paramMap);
                if (room == null) {
                    it.remove();
                    continue;
                } else {
                    icmSingle.setToUserName(room.getRnamr());
                }
            } else {
                Users toUser = usersMapper.getUserByUid(Integer.valueOf(icmSingle.getToUid()));
                if (toUser != null) {
                    icmSingle.setToUserName(toUser.getUserName());
                } else {
                    icmSingle.setToUserName("该用户不存在！");
                }
            }
            //"from ImMessage im where ((im.fromUid=? and im.toUid=?) or (im.fromUid=? and im.toUid=?)) order by im.stime desc",0,2,new Object[]{icmSingle.getFromUid(),icmSingle.getToUid(),icmSingle.getToUid(),icmSingle.getFromUid()}
            Map<String, Object> mapLastMessage = new HashMap<String, Object>();
            mapLastMessage.put("uuid", icmSingle.getUuid());
            ImMessage im = messageDao.getMessageByLast(mapLastMessage);
            if (im == null) continue;
            ImMessageModel iclm = new ImMessageModel();
            if (icmSingle.getMsgType().equals("1")) {
                iclm.setPhoto("/img/im/groupchat.png");
                //iclm.setGroupMessage(messageDao.getAllGroupMessage(icmSingle.getOfTo()));
            }else{
                Users to = new Users();
                if (icmSingle.getFromUid().equals(icmSingle.getToUid())){
                     to = usersMapper.selectUserByUId(Integer.valueOf(icmSingle.getToUid()));
                }else if (icmSingle.getFromUid().equals(user.getUid().toString())){
                    to = usersMapper.selectUserByUId(Integer.valueOf(icmSingle.getToUid()));
                }else{
                    to = usersMapper.selectUserByUId(Integer.valueOf(icmSingle.getFromUid()));
                }
                if (to!=null&&StringUtils.checkNull(to.getAvatar())&&StringUtils.checkNull(to.getAvatar128())){
                    iclm.setPhoto(StringUtils.checkNull(to.getSex())?"0":to.getSex());
                }else if (to!=null&&StringUtils.checkNull(to.getAvatar())&&!StringUtils.checkNull(to.getAvatar128())){
                    //参照控制面板上传图片模块修正avatar为小图片
                    String realPath = request.getSession().getServletContext().getRealPath("/");
                    String resourcePath = "ui/img/user";
                    Users users = new Users();
                    //上传图片并进行修改数据库数据
                    File dir = new File(realPath + resourcePath);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    File realfile = new File(dir, to.getAvatar128());
                    if (!realfile.exists()) {
                        iclm.setPhoto("0");
                    }else {
                        String fileName128 = FileUploadUtil.rename(to.getAvatar128(), "s");
                        String newImg = FileUploadUtil.zipImageFile(realfile.getAbsolutePath(), 128, 128, 1, fileName128, dir.getAbsolutePath());
                        users.setAvatar(fileName128);
                        int count = usersMapper.editUser(users);
                        iclm.setPhoto(fileName128);
                    }
                }else{
                    //参照控制面板上传图片模块修正avatar为小图片

                    if (to!=null){
                        if ("0".equals(to.getAvatar()) || "1".equals(to.getAvatar())) {
                            iclm.setPhoto(StringUtils.checkNull(to.getSex()) ? "0" : to.getSex());
                        }else{
                            String realPath = request.getSession().getServletContext().getRealPath("/");
                            String resourcePath = "ui/img/user";
                            File realfile = new File(realPath+resourcePath, to.getAvatar());
                            if (realfile.exists()) {
                                iclm.setPhoto(to.getAvatar());
                            }else{
                                iclm.setPhoto(StringUtils.checkNull(to.getSex()) ? "0" : to.getSex());
                            }
                        }

                    }else{
                        iclm.setPhoto("0");
                    }

                }
            }
            iclm.setContent(icmSingle.getLastContent());
            iclm.setFrom_uid(icmSingle.getFromUid());
            iclm.setTo_uid(icmSingle.getToUid());
            iclm.setOf_from(icmSingle.getOfFrom());
            iclm.setOf_to(icmSingle.getOfTo());
            iclm.setTime(icmSingle.getLastTime());
            iclm.setUuid(im.getUuid());
            iclm.setType(icmSingle.getType());
            iclm.setList_id(icmSingle.getListId());
            iclm.setMsg_type(icmSingle.getMsgType());
            iclm.setFormUserName(icmSingle.getFromUserName());
            iclm.setToUserName(icmSingle.getToUserName());
            //String severpath = request.getRealPath("");
            //String from_uid, String to_uid, String of_from,String content, String of_to, String uuid, String type, String file,String time
            Files file1 = new Files();
            int fileid = -1;
            if (!StringUtils.checkNull(im.getFileId())) {
                fileid = Integer.parseInt(im.getFileId());
            }
            Attachment tee = attachmentMapper.selectByPrimaryKey(fileid);
            if (tee != null) {
                String size = this.reSize(tee.getSize());
                try {
                    String path = sb.toString()  + System.getProperty("file.separator") + company +
                            System.getProperty("file.separator") + "im" + System.getProperty("file.separator") + tee.getYm() + System.getProperty("file.separator") + tee.getAttachId() + "." + tee.getAttachName();
                    String fileStr = "AID=" + tee.getAid() + "&" + "MODULE=" + "im" + "&" + "COMPANY=" + company + "&" + "YM=" + tee.getYm() + "&" + "ATTACHMENT_ID=" + tee.getAttachId() + "&" + "ATTACHMENT_NAME=" + tee.getAttachName();
                    //图片处理
                    if ("img".equals(im.getType())) {
                        String port = String.valueOf(request.getServerPort());
                        File picture = new File(path);
                        File thmpicture = new File(path);
                        FileInputStream fis = new FileInputStream(picture);
                        FileInputStream thmfis = new FileInputStream(thmpicture);
                        //获取图片大小
                        BufferedImage sourceImg = ImageIO.read(fis);
                        BufferedImage thmsourceImg = ImageIO.read(thmfis);
                        file1.setFile_url(fileStr);

                        file1.setFile_size(size);
                        file1.setFile_name(tee.getAttachName());

                        file1.setFile_width(String.valueOf(sourceImg.getWidth()));
                        file1.setFile_height(String.valueOf(sourceImg.getHeight()));
                        file1.setThumbnail_url(fileStr);

                        file1.setThumbnail_width(String.valueOf(thmsourceImg.getHeight()));
                        file1.setThumbnail_height(String.valueOf(thmsourceImg.getWidth()));
                    }
                    //text   voice     img  file
                    if ("voice".equals(im.getType())) {
                        String port = String.valueOf(request.getServerPort());
                        file1.setFile_url(fileStr);
                        file1.setVoice_time(im.getThumbnailUrl());
                    }
                    //text file
                    if ("file".equals(im.getType())) {

                        file1.setFile_url(fileStr);
                        file1.setFile_name(tee.getAttachName());
                        file1.setFile_type(tee.getAttachName().substring(tee.getAttachName().lastIndexOf(".") + 1));
                        file1.setFile_size(size);
                    }
                } catch (Exception e) {
                    L.e(e);
                    //e.printStackTrace();
                }
            }
            iclm.setFile(file1);
            iclmList.add(iclm);

        }

        return iclmList;
    }


    @Transactional(readOnly = false)
    public List<ImMessageModel> getImChatList1(HttpServletRequest request, String ofFrom, String toName, String content, Integer pageSize, Integer page, Boolean useFlag) throws FileNotFoundException, IOException, LineUnavailableException, UnsupportedAudioFileException {
        List<ImMessageModel> iclmList = new ArrayList<ImMessageModel>();
        List<Object> datas = null;
        //读取配置文件
        String company = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        String sqlType = (String) request.getSession().getAttribute(
                "loginDateSouse");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        Integer userPriv = users.getUserPriv();
        UserPriv userPriv1 = userPrivMapper.selectByPrimaryKey(userPriv);
        int str = users.getUid();
        ImMessageModel messageModel = new ImMessageModel();
        messageModel.setSqlType(sqlType);
        messageModel.setStr(str);
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        //String name = rb.getString("mysql.driverClassName");
        String osName = System.getProperty("os.name");
        StringBuffer sb = new StringBuffer();
        StringBuffer buffer = new StringBuffer();
        if (osName.toLowerCase().startsWith("win")) {
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if (uploadPath.indexOf(":") == -1) {
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if (basePath.indexOf("/xoa") != -1) {
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2 = basePath.substring(0, index);
                }
                sb = sb.append(str2 + "/xoa");
            }
            sb.append(uploadPath);
            buffer = buffer.append(rb.getString("upload.win"));
        } else {
            sb = sb.append(rb.getString("upload.linux"));
            buffer = buffer.append(rb.getString("upload.linux"));
        }
        List<Object> list = new ArrayList<Object>();
        list.add(ofFrom);
        //findByObject("from ImChatData where ofFrom=?", list)
        Map<String, Object> map = new HashMap<String, Object>();

        if (toName != null && !"".equals(toName)) {
            Users user = usersMapper.getUserByUserName(toName);
            if (user != null) {
                Integer userId = user.getUid();
                map.put("userId", userId);
            } else {
                return iclmList;
            }
        }
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(true);
        map.put("page", pageParams);
        map.put("content", content);
        //----------------wym
        if (userPriv1.getPrivType() == 1) {//如果该角色是管理员，显示全部历史消息
            datas = chatDataDao.getChatAllList(map);
        } else {//角色不是管理员
            map.put("ofFrom", ofFrom);
            datas = chatDataDao.getChatList(map);
        }
        //--------------wym
        List<Object> icm = new ArrayList<Object>();

        for (int i = 0; i < datas.size(); i++) {
            ImChatData icmSingle = (ImChatData) datas.get(i);
            List<ImMessage> imlist = new ArrayList<ImMessage>();
            //"from ImMessage im where ((im.fromUid=? and im.toUid=?) or (im.fromUid=? and im.toUid=?)) order by im.stime desc",0,2,new Object[]{icmSingle.getFromUid(),icmSingle.getToUid(),icmSingle.getToUid(),icmSingle.getFromUid()}
            Map<String, Object> mapLastMessage = new HashMap<String, Object>();
            mapLastMessage.put("uuid", icmSingle.getUuid());
            List<ImMessage> im = messageDao.getLastMessage1(mapLastMessage);
            ImMessageModel iclm = new ImMessageModel();
            iclm.setContent(icmSingle.getLastContent());
            iclm.setFrom_uid(icmSingle.getFromUid());
            iclm.setTo_uid(icmSingle.getToUid());
            iclm.setOf_from(icmSingle.getOfFrom());
            iclm.setOf_to(icmSingle.getOfTo());
            iclm.setTime(icmSingle.getLastTime());
            if (im.size() > 0) {
                iclm.setUuid(im.get(0).getUuid());
            }
            iclm.setType(icmSingle.getType());
            iclm.setList_id(icmSingle.getListId());
            iclm.setMsg_type(icmSingle.getMsgType());
            iclm.setFormUserName(icmSingle.getFromUserName());
            if(icmSingle.getToUserName()==null||icmSingle.getToUserName()==""){
                iclm.setToUserName(icmSingle.getRnamr());
            }else{
                iclm.setToUserName(icmSingle.getToUserName());
            }
            iclm.setSqlType(messageModel.getSqlType());
            iclm.setStr(messageModel.getStr());
            String severpath = request.getRealPath("");
            //String from_uid, String to_uid, String of_from,String content, String of_to, String uuid, String type, String file,String time
            Files file1 = new Files();
            int fileid = -1;
            if (im.size() > 0) {
                if ("".equals(im.get(0).getFileId()) && im.get(0).getFileId() != null && !"".equals(im.get(0).getFileId())) {
                    fileid = Integer.parseInt(im.get(0).getFileId());
                }
            }
            Attachment tee = attachmentMapper.selectByPrimaryKey(fileid);
            if (tee != null) {
                String path = sb.toString() + System.getProperty("file.separator") + "attach" + System.getProperty("file.separator") + company +
                        System.getProperty("file.separator") + "im" + System.getProperty("file.separator") + tee.getYm() + System.getProperty("file.separator") + tee.getAttachId() + "/" + tee.getAttachName();
                String fileStr = "AID=" + tee.getAid() + "&" + "MODULE=" + "im" + "&" + "COMPANY=" + company + "&" + "YM=" + tee.getYm() + "&" + "ATTACHMENT_ID=" + tee.getAttachId() + "&" + "ATTACHMENT_NAME=" + tee.getAttachName();
            /*	String ip = "";
                SysPara sysPara3 = sysParaMapper.querySysPara("IM_HOST");
				//根据商量先获取数据库IM_HOST的字段是否为空 如果不为空 返回IM_HOST的IP
				if(sysPara3!=null&&!StringUtils.checkNull(sysPara3.getParaValue())){
					ip=sysPara3.getParaValue();
				}else {
					SysPara sysPara2 = sysParaMapper.querySysPara("IM_STUTES");
					if(one.equals(sysPara2.getParaValue())){
						ip = IpAddr.getV4IP();
					}else{
						ip = IpAddr.getCurrentIp().getHostAddress();
					}
				}*/
                //图片处理
                if (im != null) {
                    if ("img".equals(im.get(0).getType())) {

                        String port = String.valueOf(request.getServerPort());
//					String fileString="/"+"imAttach"+"/"+(tee.getAttachFile()==null?"":tee.getAttachFile()).replace("\\", "/");
                        File picture = new File(path);
                        File thmpicture = new File(path);
                        if (picture.exists() && thmpicture.exists()) {
                            FileInputStream fis = new FileInputStream(picture);
                            FileInputStream thmfis = new FileInputStream(thmpicture);
                            //获取图片大小
                            long size = fis.getChannel().size();
                            long thmsize = thmfis.getChannel().size();
                            BufferedImage sourceImg = ImageIO.read(fis);
                            BufferedImage thmsourceImg = ImageIO.read(thmfis);
                            file1.setFile_url(fileStr);
                            double size_k = size / 1024;
                            BigDecimal l = new BigDecimal(Double.toString(size_k));
                            double res = l.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            long ress = 0;
                            if (size_k < 1024 && size_k > 0) {
                                if (Math.round(res) - res == 0) {
                                    ress = (long) res;
                                }
                                file1.setFile_size(String.valueOf(ress) + "KB");
                            } else if (size_k >= 1024) {
                                double size_m = size_k / 1024;
                                BigDecimal lm = new BigDecimal(Double.toString(size_k));
                                double res_m = l.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                                long resss = 0;
                                if (Math.round(res_m) - res_m == 0) {
                                    resss = (long) res_m;
                                }
                                file1.setFile_size(String.valueOf(resss) + "MB");
                            }
                            file1.setFile_width(String.valueOf(sourceImg.getWidth()));
                            file1.setFile_height(String.valueOf(sourceImg.getHeight()));
                            file1.setThumbnail_url(fileStr);
                            if (size_k < 1024 && size_k > 0) {
                                if (Math.round(res) - res == 0) {
                                    ress = (long) res;
                                }
                                file1.setThumbnail_size(String.valueOf(ress) + "KB");
                            } else if (size_k >= 1024) {
                                double size_m = size_k / 1024;
                                BigDecimal lm = new BigDecimal(Double.toString(size_k));
                                double res_m = l.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                                long resss = 0;
                                if (Math.round(res_m) - res_m == 0) {
                                    resss = (long) res_m;
                                }
                                file1.setThumbnail_size(String.valueOf(resss) + "MB");
                            }
                            file1.setThumbnail_width(String.valueOf(thmsourceImg.getHeight()));
                            file1.setThumbnail_height(String.valueOf(thmsourceImg.getWidth()));

                        }

                    }
                    //text   voice     img  file
                    if ("voice".equals(im.get(0).getType())) {

                        String port = String.valueOf(request.getServerPort());
//					String fileString="/"+"imAttach"+"/"+(tee.getAttachFile()==null?"":tee.getAttachFile()).replace("\\", "/");
                        file1.setFile_url(fileStr);
                        file1.setVoice_time(im.get(0).getThumbnailUrl());
                    }
                    //text file
                    if ("file".equals(im.get(0).getType())) {

                        String port = String.valueOf(request.getServerPort());
//					String fileString="/"+"imAttach"+"/"+(tee.getAttachFile()==null?"":tee.getAttachFile()).replace("\\", "/");
                        file1.setFile_url(fileStr);
                        file1.setFile_name(im.get(0).getFileName());
                        file1.setFile_type(tee.getAttachName().substring(tee.getAttachName().lastIndexOf(".") + 1));
                        File picture = new File(path);
                        if (picture.exists()) {
                            FileInputStream fis = new FileInputStream(picture);
                            long size = fis.getChannel().size();
                            double size_k = size / 1024;
                            BigDecimal l = new BigDecimal(Double.toString(size_k));
                            double res = l.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            long ress = 0;
                            if (size_k < 1024 && size_k > 0) {
                                if (Math.round(res) - res == 0) {
                                    ress = (long) res;
                                }
                                file1.setFile_size(String.valueOf(ress) + "KB");
                            } else if (size_k >= 1024) {
                                double size_m = size_k / 1024;
                                BigDecimal lm = new BigDecimal(Double.toString(size_k));
                                double res_m = l.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                                long resss = 0;
                                if (Math.round(res_m) - res_m == 0) {
                                    resss = (long) res_m;
                                }
                                file1.setFile_size(String.valueOf(resss) + "MB");
                            }
                        }
                    }
                }
            }
            iclm.setFile(file1);
            iclmList.add(iclm);

        }
        ImMessageModel im1 = new ImMessageModel();
        im1.setStr(pageParams.getTotal());
        iclmList.add(im1);
        return iclmList;
    }

    /**
     * @return
     * @作者 韩东堂
     * @创建日期 2017-4-26 下午1:58:29
     * @方法介绍 消息撤回
     * @参数说明 @param uuid 要撤回的消息的uuid
     * @参数说明 @return ToJson
     */
    @Transactional(readOnly = false)
    public ToJson<ImMessage> rollBackMessage(String uuid) {
        // 删除此消息
        ToJson<ImMessage> json = new ToJson<>(1, "error");
        if (StringUtils.checkNull(uuid)) {
            json.setMsg("缺少必要参数uuid");
            return json;
        }
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("uuid", uuid);
            map.put("type", "withdraw");
            int count = messageDao.upMessageByType(map);
            if (count > 0) {
                json.setFlag(0);
                json.setMsg("ok");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-5-23 下午4:58:17
     * 方法介绍:   取得历史消息
     * 参数说明:   @param request
     * 参数说明:   @param from_uid
     * 参数说明:   @param to_uid
     * 参数说明:   @param last_time
     * 参数说明:   @return
     * 参数说明:   @throws FileNotFoundException
     * 参数说明:   @throws IOException
     * 参数说明:   @throws LineUnavailableException
     * 参数说明:   @throws UnsupportedAudioFileException
     *
     * @return List<ImMessageModel>
     */
    @Transactional(readOnly = false)
    public ToJson<ImMessageModel> showMessageList(HttpServletRequest request, String from_uid, String to_uid, String last_time, String msg_type, Integer pagenum) throws FileNotFoundException, IOException, LineUnavailableException, UnsupportedAudioFileException {
        ToJson<ImMessageModel> toJson = new ToJson<>();
        List<ImMessageModel> list = new ArrayList<ImMessageModel>();
    /*	String checkResult = StringUtils.checkNullUtils(
                new CheckCallBack() {
					@Override
					public boolean isNull(Object obj) {
						// TODO Auto-generated method stub
						if (obj instanceof String) {
							String a = (String) obj;
							if (a == null || "".equals(a)
									|| a.length() == 0)
								return true;
						}
						if (obj instanceof Integer) {
							Integer a = (Integer) obj;
							if (a == null)
								return true;
						}
						return false;
					}
				}, from_uid, "from_uid不能为空", to_uid,
				"to_uid不能为空", last_time, "last_time不能为空");*/
        String checkResult = StringUtils.checkNullUtils(
                new CheckCallBack() {
                    @Override
                    public boolean isNull(Object obj) {
                        // TODO Auto-generated method stub
                        if (obj instanceof String) {
                            String a = (String) obj;
                            if (a == null || "".equals(a)
                                    || a.length() == 0)
                                return true;
                        }
                        if (obj instanceof Integer) {
                            Integer a = (Integer) obj;
                            if (a == null)
                                return true;
                        }
                        return false;
                    }
                }, to_uid,
                "to_uid不能为空");
        if (checkResult != null) {
            toJson.setMsg(checkResult);
            return toJson;
        }
        List<ImMessage> datas = null;//((FROM_UID=#{fromId} AND TO_UID =#{toId}) OR (FROM_UID=#{toId} AND TO_UID =#{fromId})) AND #{lastTime} >= ATIME  ORDER BY ATIME
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fromId", from_uid);
        if (!StringUtils.checkNull(last_time)) {
            map.put("lastTime", Double.parseDouble(last_time));
        }
        map.put("toId", to_uid);
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(true);
        pageParams.setPage(pagenum);
        pageParams.setPageSize(30);
        //默认 30条数据
        map.put("page", pageParams);
        if ("0".equals(msg_type)) {
            if (StringUtils.checkNull(last_time)) {
                datas = messageDao.selectMessageByPageAll(map);
            } else {
                datas = messageDao.selectMessageByPage(map);
            }
        } else {
            if (StringUtils.checkNull(last_time)) {
                datas = messageDao.getGroupMessageAll(map);
            } else {
                datas = messageDao.getGroupMessage(map);
            }
        }

        //读取配置文件
        String company = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        //String name = rb.getString("mysql.driverClassName");
        String osName = System.getProperty("os.name");
        StringBuffer sb = new StringBuffer();
        StringBuffer buffer = new StringBuffer();
        if (osName.toLowerCase().startsWith("win")) {
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if (uploadPath.indexOf(":") == -1) {
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if (basePath.indexOf("/xoa") != -1) {
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2 = basePath.substring(0, index);
                }
                sb = sb.append(str2 + "/xoa");
            }
            sb.append(uploadPath);
            buffer = buffer.append(rb.getString("upload.win"));
        } else {
            sb = sb.append(rb.getString("upload.linux"));
            buffer = buffer.append(rb.getString("upload.linux"));
        }
        for (ImMessage im : datas) {
            Files file1 = new Files();
            Attachment tee = null;
            if (im.getFileId() != null && !"".equals(im.getFileId())) {
                tee = attachmentMapper.selectByPrimaryKey(Integer.parseInt(im.getFileId()));
            }
            if (tee != null) {
                String path = sb.toString() + System.getProperty("file.separator") + company +
                        System.getProperty("file.separator") + "im" + System.getProperty("file.separator") + tee.getYm() + System.getProperty("file.separator") + tee.getAttachId() + "." + tee.getAttachName();
                String size1 = im.getThumbnailUrl();
                String size = "";
              /*  String[] aStrings = size1.split("&");
                for (int i = 0; i < aStrings.length; i++) {
                    if (aStrings[i].contains("FILESIZE")) {
                        String[] s = aStrings[i].split("=");
                        size = s[1];
                        break;
                    }
                }*/
                //获取对应附件或图片声音的大小
                size = this.reSize(tee.getSize());

                String fileStr = "AID=" + tee.getAid() + "&" + "MODULE=" + "im" + "&" + "COMPANY=" + company + "&" + "YM=" + tee.getYm() + "&" + "ATTACHMENT_ID=" + tee.getAttachId() + "&" + "ATTACHMENT_NAME=" + tee.getAttachName()
                        + "&" + "FILESIZE=" + size;
                if ("img".equals(im.getType())) {
                    try {
                        String port = String.valueOf(request.getServerPort());
                        File picture = new File(path);
                        File thmpicture = new File(path);
                        FileInputStream fis = new FileInputStream(picture);
                        FileInputStream thmfis = new FileInputStream(thmpicture);
                        //获取图片大小
                        //	long size=fis.getChannel().size();
                        long thmsize = thmfis.getChannel().size();
                        BufferedImage sourceImg = ImageIO.read(fis);
                        BufferedImage thmsourceImg = ImageIO.read(thmfis);
                        file1.setFile_url(fileStr);

                        file1.setFile_size(size);
                        file1.setFile_name(tee.getAttachName());
                        file1.setFile_width(String.valueOf(sourceImg.getWidth()));
                        file1.setFile_height(String.valueOf(sourceImg.getHeight()));
                        file1.setThumbnail_url(fileStr);
                        file1.setThumbnail_size(size);
                        file1.setThumbnail_width(String.valueOf(thmsourceImg.getHeight()));
                        file1.setThumbnail_height(String.valueOf(thmsourceImg.getWidth()));
                        fis.close();

                    } catch (Exception e) {

                    }
                }
                //text   voice     img  file
                if ("voice".equals(im.getType())) {

                    //String port = String.valueOf(request.getServerPort());
                    file1.setFile_url(fileStr);
                    file1.setVoice_time(im.getThumbnailUrl());
                }
                //text file
                if ("file".equals(im.getType())) {
                    try {
                        //String port = String.valueOf(request.getServerPort());
                        file1.setFile_url(fileStr);
                        file1.setFile_name(tee.getAttachName());
                        file1.setFile_type(tee.getAttachName().substring(tee.getAttachName().lastIndexOf(".") + 1));
                        // File picture = new File(path);
                        //FileInputStream fis = new FileInputStream(picture);
                        file1.setFile_size(size);
                        //fis.close();

                    } catch (Exception e) {

                    }

                }
            }
            Users userByuid = usersService.findUserByuid(Integer.parseInt(im.getFromUid()));
            String fromUserName = "已删除用户";
            if (userByuid != null && userByuid.getUserName() != null) {
                fromUserName = userByuid.getUserName();
            }
            String toUserName = "已删除用户";
            if ("0".equals(msg_type)) {
                Users userByuid1 = usersService.findUserByuid(Integer.parseInt(im.getToUid()));
                if (userByuid1 != null && userByuid1.getUserName() != null) {
                    toUserName = userByuid1.getUserName();
                }
            } else {
                Map<String, String> room = new HashMap<>();
                room.put("roomOf", im.getToUid());
                ImRoom roomByRoomOf = roomDao.getRoomByRoomOf(room);
                if (roomByRoomOf != null) {
                    toUserName = roomByRoomOf.getRnamr();
                }
            }
            ImMessageModel imm = new ImMessageModel(im.getFromUid()
                    , im.getToUid()
                    , im.getOfFrom()
                    , im.getContent()
                    , im.getOfTo()
                    , im.getUuid()
                    , im.getType()
                    , file1
                    , im.getStime());
            imm.setFormUserName(fromUserName);
            imm.setToUserName(toUserName);
            imm.setMsg_type(im.getMsgType());
            list.add(imm);
        }

        toJson.setTotleNum(pageParams.getTotal());
        toJson.setFlag(0);
        toJson.setObj(list);
        toJson.setMsg("ok");

        return toJson;

    }

    @Transactional(readOnly = false)
    public ToJson<ImMessageModel> showMessageListRiLeGou(HttpServletRequest request, String from_uid, String to_uid, String last_time, String msg_type, Integer pagenum, String type, String fileName, String searchMsg) throws FileNotFoundException, IOException, LineUnavailableException, UnsupportedAudioFileException {
        ToJson<ImMessageModel> toJson = new ToJson<>();
        List<ImMessageModel> list = new ArrayList<ImMessageModel>();
        String checkResult = StringUtils.checkNullUtils(
                new CheckCallBack() {
                    @Override
                    public boolean isNull(Object obj) {
                        // TODO Auto-generated method stub
                        if (obj instanceof String) {
                            String a = (String) obj;
                            if (a == null || "".equals(a)
                                    || a.length() == 0)
                                return true;
                        }
                        if (obj instanceof Integer) {
                            Integer a = (Integer) obj;
                            if (a == null)
                                return true;
                        }
                        return false;
                    }
                }, to_uid,
                "to_uid不能为空", last_time, "last_time不能为空");
        if (checkResult != null) {
            return null;
        }
//		String uid,toId;
//		try{
//			uid=from_uid.split("pq")[1];
//		}catch (Exception e){
//			uid=from_uid;
//		}
//		try{
//			toId=to_uid.split("pq")[1];
//		}catch (Exception e){
//			toId=to_uid.split("pq")[1];
//		}
        List<ImMessage> datas = null;//((FROM_UID=#{fromId} AND TO_UID =#{toId}) OR (FROM_UID=#{toId} AND TO_UID =#{fromId})) AND #{lastTime} >= ATIME  ORDER BY ATIME
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fromId", from_uid);
        map.put("lastTime", last_time);
        map.put("toId", to_uid);
        map.put("type", type);
        map.put("fileName", fileName);
        map.put("searchMsg", searchMsg);
//		map.put("pageNo",1);
//		map.put("pageSize",20);
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(true);
        pageParams.setPage(pagenum);
        pageParams.setPageSize(10);
        map.put("page", pageParams);
//		datas=messageDao.getMessageList(map);
       if (StringUtils.checkNull(msg_type) || "0".equals(msg_type)){
        //if ("0".equals(msg_type)) {
            datas = messageDao.selectMessageByPage(map);
        } else {
            datas = messageDao.getGroupMessage(map);
        }

        //读取配置文件
        String company = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        //String name = rb.getString("mysql.driverClassName");
        String osName = System.getProperty("os.name");
        StringBuffer sb = new StringBuffer();
        StringBuffer buffer = new StringBuffer();
        if (osName.toLowerCase().startsWith("win")) {
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if (uploadPath.indexOf(":") == -1) {
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if (basePath.indexOf("/xoa") != -1) {
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2 = basePath.substring(0, index);
                }
                sb = sb.append(str2 + "/xoa");
            }
            sb.append(uploadPath);
            buffer = buffer.append(rb.getString("upload.win"));
        } else {
            sb = sb.append(rb.getString("upload.linux"));
            buffer = buffer.append(rb.getString("upload.linux"));
        }
        for (ImMessage im : datas) {
            //String from_uid, String to_uid, String of_from,String content, String of_to, String uuid, String type, String file,String time
            //图片处理
            //String from_uid, String to_uid, String of_from,String content, String of_to, String uuid, String type, String file,String time
            Files file1 = new Files();
            //图片处理
//			int fileid=-1;
//			if(!StringUtils.checkNull(im.getFileId())){
//				fileid=Integer.parseInt(im.getFileId());
//			}
            Attachment realTee = null;
            Attachment thumBanllTee = null;

           /* if (im.getFileId() != null && !"".equals(im.getFileId())) {
                tee = attachmentMapper.selectByPrimaryKey(Integer.parseInt(im.getFileId()));
            }*/
            if (!StringUtils.checkNull(im.getRealUrl()) && im.getRealUrl().contains("&")) {
                String[] aidStr = im.getRealUrl().split("&");
                if (aidStr.length > 1 && aidStr[0].contains("=")) {
                    String[] aidArr = aidStr[0].split("=");
                    if (aidArr.length > 0) {
                        realTee = attachmentMapper.selectByPrimaryKey(Integer.parseInt(aidArr[1]));
                    }
                }
            }
            if (!StringUtils.checkNull(im.getThumbnailUrl()) && im.getThumbnailUrl().contains("&")) {
                String[] aidStr = im.getThumbnailUrl().split("&");
                if (aidStr.length > 1 && aidStr[0].contains("=")) {
                    String[] aidArr = aidStr[0].split("=");
                    if (aidArr.length > 0) {
                        thumBanllTee = attachmentMapper.selectByPrimaryKey(Integer.parseInt(aidArr[1]));
                    }
                }
            }
            if (!"img".equals(im.getType())) {
                String[] aidStr = im.getThumbnailUrl().split("&");
                if (aidStr.length > 1 && aidStr[0].contains("=")) {
                    String[] aidArr = aidStr[0].split("=");
                    if (aidArr.length > 0) {
                        realTee = attachmentMapper.selectByPrimaryKey(Integer.parseInt(aidArr[1]));
                    }
                }
            }
            if (realTee != null) {
                String size = realTee.getSize();
                if (!StringUtils.checkNull(size)) {
                    if (size.contains("MB")) {
                        //size.replace("MB"," ");
                        size = size;
                    } else if (size.contains("KB")) {
                        //size.replace("KB"," ");
                        size = size;
                    } else {
                        //size.replace("B"," ");
                        //size = String.valueOf(Integer.parseInt(size.trim())/1000);
                        double temp = Double.parseDouble(size.substring(0, size.length() - 1).trim()) / 1024;
                        ;
                        temp = temp > 0.01 ? (double) Math.round(temp * 100) / 100 : 0.01;
                        size = String.valueOf(temp) + " KB";
                        //size = String.valueOf(Double.parseDouble( size.substring( 0, size.length()-1 ).trim())/1024) + " KB";
                    }
                } else {
                    size = "0";
                }
                String realPath = sb.toString() + System.getProperty("file.separator") + company +
                        System.getProperty("file.separator") + "im" + System.getProperty("file.separator") + realTee.getYm() + System.getProperty("file.separator") + realTee.getAttachId() + "." + realTee.getAttachName();
                String realFileStr = "AID=" + realTee.getAid() + "&" + "MODULE=" + "im" + "&" + "COMPANY=" + company + "&" + "YM=" + realTee.getYm() + "&" + "ATTACHMENT_ID=" + realTee.getAttachId() + "&" + "ATTACHMENT_NAME=" + realTee.getAttachName();

            /*    String thumbnailSize = im.getThumbnailUrl();
                String[] thumbnailSizeArr = thumbnailSize.split("&");
                for (int i = 0; i < thumbnailSizeArr.length; i++) {
                    if (thumbnailSizeArr[i].contains("FILESIZE")) {
                        String[] s = thumbnailSizeArr[i].split("=");
                        thumbnailSize = s[1];
                        break;
                    }
                }

                String realSize = im.getRealUrl();
                String[] realSizeArr = realSize.split("&");
                for (int i = 0; i < realSizeArr.length; i++) {
                    if (realSizeArr[i].contains("FILESIZE")) {
                        String[] s = realSizeArr[i].split("=");
                        realSize = s[1];
                        break;
                    }
                }*/

                if ("img".equals(im.getType())) {
                    try {
                        String port = String.valueOf(request.getServerPort());
                        File picture = new File(realPath);
                        FileInputStream fis = new FileInputStream(picture);
                        //获取图片大小
                        BufferedImage sourceImg = ImageIO.read(fis);
                        file1.setFile_url(realFileStr);
                        file1.setFile_size(size);
                        file1.setFile_name(realTee.getAttachName());
                        file1.setFile_width(String.valueOf(sourceImg.getWidth()));
                        file1.setFile_height(String.valueOf(sourceImg.getHeight()));
                        if (thumBanllTee != null) {
                            String thumBanllPath = sb.toString() + System.getProperty("file.separator") + company +
                                    System.getProperty("file.separator") + "im" + System.getProperty("file.separator") + thumBanllTee.getYm() + System.getProperty("file.separator") + thumBanllTee.getAttachId() + "." + thumBanllTee.getAttachName();
                            String thumBanllFileStr = "AID=" + thumBanllTee.getAid() + "&" + "MODULE=" + "im" + "&" + "COMPANY=" + company + "&" + "YM=" + thumBanllTee.getYm() + "&" + "ATTACHMENT_ID=" + thumBanllTee.getAttachId() + "&" + "ATTACHMENT_NAME=" + thumBanllTee.getAttachName();
                            File thmpicture = new File(thumBanllPath);
                            FileInputStream thmfis = new FileInputStream(thmpicture);
                            //long thmsize = thmfis.getChannel().size();
                            BufferedImage thmsourceImg = ImageIO.read(thmfis);
                            file1.setThumbnail_url(thumBanllFileStr);
                            file1.setThumbnail_size(size);
                            file1.setThumbnail_width(String.valueOf(thmsourceImg.getHeight()));
                            file1.setThumbnail_height(String.valueOf(thmsourceImg.getWidth()));
                        }
                        fis.close();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }
                //text   voice     img  file
                if ("voice".equals(im.getType())) {

                    String port = String.valueOf(request.getServerPort());
                    file1.setFile_url(realFileStr);
                    file1.setVoice_time(im.getThumbnailUrl());
                }
                //text file
                if ("file".equals(im.getType())) {

                /*    realSize = im.getThumbnailUrl();
                    String[] realSizeArr2 = realSize.split("&");
                    for (int i = 0; i < realSizeArr2.length; i++) {
                        if (realSizeArr2[i].contains("FILESIZE")) {
                            String[] s = realSizeArr2[i].split("=");
                            realSize = s[1];
                            break;
                        }
                    }*/

                    try {
                        String port = String.valueOf(request.getServerPort());
                        file1.setFile_url(realFileStr);
                        file1.setFile_name(realTee.getAttachName());
                        file1.setFile_type(realTee.getAttachName().substring(realTee.getAttachName().lastIndexOf(".") + 1));
                        //File picture = new File(realPath);
                        // FileInputStream fis = new FileInputStream(picture);
                        file1.setFile_size(size);
                        // fis.close();

                    } catch (Exception e) {

                    }

                }
            }
            String fromUserName1 = usersService.findUserByuid(Integer.parseInt(im.getFromUid())).getUserName();
            if (fromUserName1 == null) {
                //System.out.println(im.getFromUid());
            }
            String fromUserName = usersService.findUserByuid(Integer.parseInt(im.getFromUid())).getUserName();
            String toUserName = "";
            if ("0".equals(msg_type)) {
                toUserName = usersService.findUserByuid(Integer.parseInt(im.getToUid())).getUserName();
            } else {
                Map<String, String> room = new HashMap<>();
                room.put("roomOf", im.getToUid());
                if (roomDao.getRoomByRoomOf(room) != null) {
                    toUserName = roomDao.getRoomByRoomOf(room).getRnamr();
                }
            }
            ImMessageModel imm = new ImMessageModel(im.getFromUid()
                    , im.getToUid()
                    , im.getOfFrom()
                    , im.getContent()
                    , im.getOfTo()
                    , im.getUuid()
                    , im.getType()
                    , file1
                    , im.getStime());
            imm.setFormUserName(fromUserName);
            imm.setToUserName(toUserName);
            list.add(imm);
        }
        try {
            if (type != null && type.trim().equals("img")) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Map<String, Set<ImMessageModel>> dataMap = new HashMap<String, Set<ImMessageModel>>();
                Set<ImMessageModel> data = null;
                List<String> dateStrList = new ArrayList<String>();
                List<ImMessageModel> list2 = list;
                Iterator<ImMessageModel> it = list.iterator();
                while (it.hasNext()) {
                    data = new HashSet<ImMessageModel>();
                    ImMessageModel imMessageModel = it.next();
                    long l;
                    if (imMessageModel.getTime().indexOf(".") > 0) {
                        l = Long.parseLong(imMessageModel.getTime().substring(0, imMessageModel.getTime().indexOf("."))) * 1000;
                    } else {
                        l = Long.parseLong(imMessageModel.getTime()) * 1000;
                    }
                    Date parse = format.parse(format.format(l));
                    Calendar ca0 = Calendar.getInstance();  //如果给的Date对象date，就忽略上句
                    ca0.setTime(parse);
                    for (int j = 0; j < list2.size(); j++) {
                        ImMessageModel imMessageModel1 = list2.get(j);
                        long l2;
                        if (imMessageModel1.getTime().indexOf(".") > 0) {
                            l2 = Long.parseLong(imMessageModel1.getTime().substring(0, imMessageModel1.getTime().indexOf("."))) * 1000;
                        } else {
                            l2 = Long.parseLong(imMessageModel1.getTime()) * 1000;
                        }
                        Date date2 = format.parse(format.format(l2));
                        Calendar ca1 = Calendar.getInstance();
                        ca1.setTime(date2);
                        //获取ca0和ca1的年，月，日，对比是否相同
                        if (ca0.get(Calendar.YEAR) == ca1.get(Calendar.YEAR) &&
                                ca0.get(Calendar.MONTH) == ca1.get(Calendar.MONTH) &&
                                ca0.get(Calendar.DAY_OF_MONTH) == ca1.get(Calendar.DAY_OF_MONTH)) {
                            data.add(imMessageModel);
                            data.add(imMessageModel1);
                        } else {
                            data.add(imMessageModel);
                        }
                    }
                    String dateStr = ca0.get(Calendar.YEAR) + "-" + (ca0.get(Calendar.MONTH) + 1) + "-" + ca0.get(Calendar.DAY_OF_MONTH);
                    if (dataMap.get(dateStr) == null) {
                        dateStrList.add(dateStr);
                        dataMap.put(dateStr, data);
                    }
                }
                toJson.setObj1(dateStrList);
                toJson.setObject(dataMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        toJson.setTotleNum(pageParams.getTotal());
        toJson.setFlag(0);
        toJson.setObj(list);
        toJson.setMsg("ok");

        return toJson;
    }

    @Transactional(readOnly = false)
    public List<ImRoomModel> getAllRoom(String of_from) {
        List<ImRoomModel> alist = new ArrayList<ImRoomModel>();
        if (of_from == null || "".equals(of_from)) {
            return null;
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("roomOf", of_from);
        Users u = usersMapper.getByUid(Integer.parseInt(of_from));
        List<ImRoom> list = roomDao.getAllRoom(map);
        if (u != null && u.getUserId() != null) {
            if (u.getUserId().equals("admin")) {
                list = roomDao.getAllRoomByAdmin();
            }
        }
        for (ImRoom ir : list) {
            /*String rNAME, String rOOM_OF, String rMEMBER_UID,
            String rOUT_UID, String rSET_UID, String rSET_OFID, String rTIME,
			String tYPE, String rCHANGE, String rINVITE*/
            String[] rmemberUid = ir.getRmemberUid().split(",");
            List<String> rmemberUidString = Arrays.asList(rmemberUid);
            ImRoomModel irm = new ImRoomModel(
                    ir.getRid(),
                    ir.getRnamr()
                    , ir.getRsetOfid()
                    , ir.getRmemberUid()
                    , ir.getRoutUid()
                    , ir.getRsetUid()
                    , ir.getRsetOfid()
                    , ir.getRtime()
                    , rmemberUidString.contains(of_from) ? "1" : "0"
                    , ir.getRchange()
                    , ir.getRinvite()
                    , ir.getRoomOf(), ir.getRoomStatus(),
                    ir.getRoomNo()
                    , ir.getRoomRemark(), ir.getRoomIntroduce());
            alist.add(irm);
        }
        for (ImRoomModel imRoomModel : alist) {
            String rmember_uid = imRoomModel.getRmember_uid();
            String rset_uid = imRoomModel.getRset_uid();
            if (rmember_uid != null && rmember_uid.endsWith(",")) {
                rmember_uid = rmember_uid.substring(0, rmember_uid.length() - 1);
            }
            if (rset_uid != null && rset_uid.endsWith(",")) {
                rset_uid = rset_uid.substring(0, rset_uid.length() - 1);
            }
            try {
                String name = usersService.findUsersByuidReturn(rmember_uid);
                String name1 = usersService.findUsersByuidReturn(rset_uid);
                imRoomModel.setRmemberUidName(name);
                imRoomModel.setRsetUidName(name1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return alist;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-5-23 下午4:59:46
     * 方法介绍:   取得单个房间信息
     * 参数说明:   @param room_id
     * 参数说明:   @return
     *
     * @return ImRoomModel
     */
    @Transactional(readOnly = false)
    public ImRoomModel getSingleRoom(String room_id) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("roomOf", room_id);
        ImRoom irm = roomDao.getRoomByRoomOf(map);
        ImRoomModel ir = new ImRoomModel();
        if (irm != null) {
            ir = new ImRoomModel(irm.getRid(), irm.getRnamr(), irm.getRoomOf(), irm.getRmemberUid(), irm.getRoutUid(), irm.getRsetUid()
                    , irm.getRsetOfid(), irm.getRtime(), "1", irm.getRchange(), irm.getRinvite(), irm.getRoomOf(), irm.getRoomStatus(), irm.getRoomNo(), irm.getRoomRemark(), irm.getRoomIntroduce());

//            StringBuffer sbUserId=new StringBuffer();
//            StringBuffer sbUserName=new StringBuffer();
//            if(!StringUtils.checkNull(irm.getRmemberUid())){
//                List<Users> users = usersMapper.getAllInfo();
//                String[] arr=irm.getRmemberUid().split(",");
//                for(String uid:arr){
//                    if(!StringUtils.checkNull(uid)){
//                        for(Users us:users){
//                            if(Integer.valueOf(uid)==us.getUid()){
//                                sbUserId.append(us.getUserId()+",");
//                                sbUserName.append(us.getUserName()+",");
//                                break;
//                            }
//                        }
//                    }
//                }
//            }

            StringBuffer rmemberUserId = new StringBuffer("");
            List<Users> userss = usersService.getUserByuId(irm.getRmemberUid());
            if (userss != null && userss.size() > 0) {
                for (Users u : userss) {
                    rmemberUserId.append(u.getUserId());
                    rmemberUserId.append(",");
                    if(u.getUid().equals(Integer.parseInt(irm.getRsetUid()))){
                        ir.setRsetUserId(u.getUserId());
                    }
                }
            }
            ir.setRmember_userId(rmemberUserId.toString());
            String rmember_uid = irm.getRmemberUid();
            if (rmember_uid != null && rmember_uid.endsWith(",")) {
                rmember_uid = rmember_uid.substring(0, rmember_uid.length() - 1);
            }
            String name = usersService.findUsersByuidReturn(rmember_uid);

            ir.setRmemberUidName(name);
            String name1 = usersService.findUsersByuidReturn(ir.getRset_uid());
            ir.setRsetUidName(name1);
        }
        return ir;
    }

    @Transactional(readOnly = false)
    public Status openInvite(String room_id, String check) {
        Status s = new Status();
        try {
            Map<String, String> map = new HashMap<String, String>();
            map.put("roomOf", room_id);
            map.put("check", check);
            int i = roomDao.roomUpdateInvite(map);
            if (i == 1) {
                s.setStatus("ok");
            }
        } catch (Exception e) {
            e.printStackTrace();
            s.setStatus("error");
        }
        return s;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-5-23 下午5:00:18
     * 方法介绍:   创建一个房间
     * 参数说明:   @param name
     * 参数说明:   @param set_uid
     * 参数说明:   @param set_of
     * 参数说明:   @param member_uid
     * 参数说明:   @param stime
     * 参数说明:   @param room_of
     * 参数说明:   @return
     *
     * @return Status
     */
    @Transactional(readOnly = false)
    public Status insertRoom(HttpServletRequest request, String name, String set_uid, String set_of,
                             String member_uid, String stime, String room_of) {
        Status s = new Status();
        try {
            ImRoom ir = new ImRoom();
            ir.setRnamr(name == null ? "" : name);
            ir.setRsetUid(set_uid == null ? "" : set_uid);
            ir.setRinvite("1");
            ir.setRsetOfid(set_of == null ? "" : set_of);
            ir.setRmemberUid(member_uid == null ? "" : member_uid);
            ir.setRtime(stime == null ? "" : stime);
            ir.setRoomOf(room_of == null ? "" : room_of);
            ir.setRchange("1");
//            System.out.print(name.length());
            int i = roomDao.saveRoom(ir);
            if (i == 1) {

                String uuid = UUID.randomUUID().toString();

                StringBuilder content = new StringBuilder();

                Users userByuid = usersMapper.findUserByuid(Integer.parseInt(set_uid));

                if (userByuid != null) {
                    content.append(userByuid.getUserName()).append("创建了群:").append(name).append(",并邀请");
                }
                List<Users> usersByUidsOrder = usersMapper.getUsersByUids(member_uid.split(","));

                for (int j = 0, size = usersByUidsOrder.size(); j < size; j++) {
                    Users users = usersByUidsOrder.get(j);
                    if (users != null && !StringUtils.checkNull(users.getUserName())) {
                        if (j + 1 != size) {
                            content.append(users.getUserName() + "、");
                        } else {
                            content.append(users.getUserName() + "加入本群。");
                        }
                    }
                }

                putMessageInfo(null, request, 1, set_uid, room_of, set_of, room_of, content.toString(), "text", stime, uuid, "1", null, new Date().getTime());

                s.setStatus("ok");
            }
        } catch (Exception e) {
            e.printStackTrace();
            s.setStatus("error");
            return s;
        }
        return s;
    }

    @Transactional(readOnly = false)
    public Status deleteMessage(String deleteuuid, String uid) {
        Status s = new Status();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("uuid", deleteuuid);
            map.put("uid", uid);
            int i = messageDao.deleteByUuid(map);
            s.setStatus("ok");
        } catch (Exception e) {
            e.printStackTrace();
            s.setStatus("error");
        }
        return s;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-7-6 下午2:03:45
     * 方法介绍:
     * 参数说明:   @param room_id
     * 参数说明:   @param delete_uid
     * 参数说明:   @param opt
     * 参数说明:   @return
     *
     * @return Status
     */
    @Transactional(readOnly = false)
    public Status getOutPerson(HttpServletRequest request, String room_id, String delete_uid, String opt) {

        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users nowUser = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);

        Status s = new Status();

        try {
            Map<String, String> map = new HashMap<String, String>();
            map.put("roomOf", room_id);
            ImRoom irm = roomDao.getRoomByRoomOf(map);
            if (irm == null) {
                s.setStatus("error");
                return s;
            }
            String memberUid;
            String outUid;
            if ("1".equals(opt) && delete_uid != null) {//踢人
                memberUid = this.transfor(delete_uid, irm.getRmemberUid());
                //memberUid = memberUid.substring(0, memberUid.length() - 1);
                outUid = (irm.getRoutUid() == null || "".equals(irm.getRoutUid())) ? (delete_uid) : (irm.getRoutUid() + "," + delete_uid);
                irm.setRmemberUid(memberUid);
                irm.setRoutUid(outUid);
            } else {//散群
               /* memberUid = "";
                outUid = (irm.getRoutUid() == null ? "" : irm.getRoutUid()) + "," + (irm.getRmemberUid() == null ? "" : irm.getRmemberUid()+",");*/
                irm.setRoomStatus(-1);
            }
            int i = roomDao.roomUpdateByroomOf(irm);
            if (i == 1) {

                String uuid = UUID.randomUUID().toString();

                StringBuilder content = new StringBuilder();



                if (nowUser != null) {
                    if(!StringUtils.checkNull(nowUser.getUserName())){
                        content.append(nowUser.getUserName());
                    } else {
                        nowUser = usersMapper.findUserByuid(nowUser.getUid());
                        content.append(nowUser.getUserName());
                    }

                    if ("1".equals(opt) && delete_uid != null) {//踢人
                        List<Users> usersByUidsOrder = usersMapper.getUsersByUids(delete_uid.split(","));
                        content.append("将");
                        for (int j = 0, size = usersByUidsOrder.size(); j < size; j++) {
                            Users users = usersByUidsOrder.get(j);
                            if (users != null && !StringUtils.checkNull(users.getUserName())) {
                                if (j + 1 != size) {
                                    content.append(users.getUserName()).append("、");
                                } else {
                                    content.append(users.getUserName()).append("移出了本群。");
                                }
                            }
                        }
                    } else {//解散群
                        content.append("解散了本群。");
                    }
                }

                putMessageInfo(null, request, 1, String.valueOf(nowUser.getUid()), irm.getRoomOf(), irm.getRsetOfid(), irm.getRoomOf(), content.toString(), "text", String.valueOf(new Date().getTime() / 1000), uuid, "1", null, new Date().getTime());


                s.setStatus("ok");
            }
        } catch (Exception e) {
            s.setStatus("error");
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2018-2-6 下午3:26:45
     * 方法介绍:   群恢复（群解散后的恢复操作）
     * 参数说明:   @param room_id 群openfireId
     *
     * @return json
     */
    @Transactional(readOnly = false)
    public ToJson<ImRoom> roomRever(HttpServletRequest request, String room_id) {
        ToJson<ImRoom> json = new ToJson<>(1, "error");
        try {
            if (StringUtils.checkNull(room_id)) {
                json.setMsg("roomId不能为空");
                return json;
            }
            ImRoom room = new ImRoom();
            room.setRoomOf(room_id);
            room.setRoomStatus(0);
            int i = roomDao.roomUpdateByroomOf(room);
            if (i > 0) {

                Map<String, String> map = new HashMap<String, String>();
                map.put("roomOf", room_id);
                ImRoom irm = roomDao.getRoomByRoomOf(map);

                String uuid = UUID.randomUUID().toString();

                StringBuilder content = new StringBuilder();

                Users userByuid = usersMapper.findUserByuid(Integer.parseInt(irm.getRsetUid()));

                if (userByuid != null) {
                    content.append(userByuid.getUserName()).append("恢复了本群。");
                }

                putMessageInfo(null, request, 1, irm.getRsetUid(), irm.getRoomOf(), irm.getRsetOfid(), irm.getRoomOf(), content.toString(), "text", String.valueOf(new Date().getTime() / 1000), uuid, "1", null, new Date().getTime());


                json.setMsg("ok");
                json.setFlag(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }


    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-5-23 下午5:01:18
     * 方法介绍:   邀请人员进房间
     * 参数说明:   @param room_id
     * 参数说明:   @param invite_uid
     * 参数说明:   @return
     *
     * @return Status
     */
    @Transactional(readOnly = false)
    public Status getPersonToRoom(HttpServletRequest request, String room_id, String invite_uid) {
        Status s = new Status();

        try {
            Map<String, String> map = new HashMap<String, String>();
            map.put("roomOf", room_id);
            ImRoom irm = roomDao.getRoomByRoomOf(map);
            if (irm == null) {
                s.setStatus("error");
                return s;
            }
            //a,s,d,m
            String oldRemberUidStr = irm.getRmemberUid();
            if (!StringUtils.checkNull(oldRemberUidStr)) {
                if (oldRemberUidStr.endsWith(",")) {
                    oldRemberUidStr = oldRemberUidStr.substring(0, oldRemberUidStr.length() - 1);
                }
            }
            String newString = oldRemberUidStr + "," + invite_uid + ",";
            irm.setRmemberUid(newString);
            String outIds = this.transfor(invite_uid, irm.getRoutUid());
            irm.setRoutUid(outIds.substring(0, outIds.length() < 1 ? outIds.length() : (outIds.length() - 1)));
            int i = roomDao.updatePersonToRoom(irm);
            if (i == 1) {

                String uuid = UUID.randomUUID().toString();

                StringBuilder content = new StringBuilder();

                Users userByuid = usersMapper.findUserByuid(Integer.parseInt(irm.getRsetUid()));

                if (userByuid != null) {
                    content.append(userByuid.getUserName()).append("邀请");

                    List<Users> usersByUidsOrder = usersMapper.getUsersByUids(invite_uid.split(","));

                    for (int j = 0, size = usersByUidsOrder.size(); j < size; j++) {
                        Users users = usersByUidsOrder.get(j);
                        if (users != null && !StringUtils.checkNull(users.getUserName())) {
                            if (j + 1 != size) {
                                content.append(users.getUserName() + "、");
                            } else {
                                content.append(users.getUserName() + "加入本群。");
                            }
                        }
                    }

                }

                putMessageInfo(null, request, 1, irm.getRsetUid(), irm.getRoomOf(), irm.getRsetOfid(), irm.getRoomOf(), content.toString(), "text", String.valueOf(new Date().getTime() / 1000), uuid, "1", null, new Date().getTime());


                s.setStatus("ok");
            } else {
                s.setStatus("error");
            }
        } catch (Exception e) {
            e.printStackTrace();
            s.setStatus("error");
        }
        return s;
    }

    public static String transfor(String uid, String outId) {
        if (outId == null) {
            outId = "";
        }
        if (uid == null) {
            uid = "";
        }
        String[] outIds = outId.split(",");
        List<String> outIdList = Arrays.asList(outIds);
        String[] uids = uid.split(",");
        List<String> uidsList = Arrays.asList(uids);
        StringBuffer sb = new StringBuffer("");
        for (String s : outIdList) {
            boolean flag = false;
            for (String s2 : uidsList) {
                if (s2.equals(s)) {
                    flag = true;
                }
            }
            if (!flag) {
                sb.append(s);
                sb.append(",");
            }
        }
        return sb.toString();
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-5-23 下午5:01:52
     * 方法介绍:   修改房间名称
     * 参数说明:   @param room_id
     * 参数说明:   @param room_name
     * 参数说明:   @return
     *
     * @return Status
     */
    @Transactional(readOnly = false)
    public Status updateRoomName(String room_id, String room_name, Integer roomNo, String roomRemark, String roomIntroduce) {
        Status s = new Status();

        try {
            Map<String, String> map = new HashMap<String, String>();
            map.put("roomOf", room_id);
            ImRoom irm = roomDao.getRoomByRoomOf(map);
            if (irm == null) {
                s.setStatus("error");
                return s;
            }
            irm.setRnamr(room_name);
            irm.setRoomNo(roomNo);
            irm.setRoomIntroduce(roomIntroduce);
            irm.setRoomRemark(roomRemark);
            int i = roomDao.updateRoomName(irm);
            if (i == 1) {
                s.setStatus("ok");
            }
        } catch (Exception e) {
            e.printStackTrace();
            s.setStatus("error");
        }
        return s;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-6-22 上午11:20:33
     * 方法介绍:   获取某个来聊天内的全部附件
     * 参数说明:   @param other_id
     * 参数说明:   @param my_uid
     * 参数说明:   @return
     *
     * @return List<Files>
     * @throws IOException
     */
    public List<ImMessageModel> getAttchments(String other_id, String my_uid, HttpServletRequest req) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("my_uid", my_uid);
        map.put("other_id", other_id);
        List<ImMessage> attMessageList = messageDao.getAttchments(map);
        List<ImMessageModel> messageList = new ArrayList<ImMessageModel>();
        for (ImMessage im : attMessageList) {
            ImMessageModel imm = this.getMessage(im, req);
            messageList.add(imm);
        }
        return messageList;
    }

    //生成返回信息
    public ImMessageModel getMessage(ImMessage im, HttpServletRequest request) throws IOException {
        //读取配置文件
        String company = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        //String name = rb.getString("mysql.driverClassName");
        String osName = System.getProperty("os.name");
        StringBuffer sb = new StringBuffer();
        StringBuffer buffer = new StringBuffer();
        if (osName.toLowerCase().startsWith("win")) {
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if (uploadPath.indexOf(":") == -1) {
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if (basePath.indexOf("/xoa") != -1) {
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2 = basePath.substring(0, index);
                }
                sb = sb.append(str2 + "/xoa");
            }
            sb.append(uploadPath);
            buffer = buffer.append(rb.getString("upload.win"));
        } else {
            sb = sb.append(rb.getString("upload.linux"));
            buffer = buffer.append(rb.getString("upload.linux"));
        }
        //String basePath="D:"+System.getProperty("file.separator");


//		String severpath=request.getRealPath("");
        Files file1 = new Files();
        //图片处理
        int fileid = -1;
        if (!StringUtils.checkNull(im.getFileId())) {
            fileid = Integer.parseInt(im.getFileId());
        }
        Attachment tee = attachmentMapper.selectByPrimaryKey(fileid);
        if (tee != null) {
            String size = this.reSize(tee.getSize());
            String path = sb.toString() + System.getProperty("file.separator") + "attach" + System.getProperty("file.separator") + company +
                    System.getProperty("file.separator") + "im" + System.getProperty("file.separator") + tee.getYm() + System.getProperty("file.separator") + tee.getAttachId() + "." + tee.getAttachName();
            String fileStr = "AID=" + tee.getAid() + "&" + "MODULE=" + "im" + "&" + "COMPANY=" + company + "&" + "YM=" + tee.getYm() + "&" + "ATTACHMENT_ID=" + tee.getAttachId() + "&" + "ATTACHMENT_NAME=" + tee.getAttachName();

		/*	String ip = "";
			SysPara sysPara3 = sysParaMapper.querySysPara("IM_HOST");
			//根据商量先获取数据库IM_HOST的字段是否为空 如果不为空 返回IM_HOST的IP
			if(sysPara3!=null&&!StringUtils.checkNull(sysPara3.getParaValue())){
				ip=sysPara3.getParaValue();
			}else {
				SysPara sysPara2 = sysParaMapper.querySysPara("IM_STUTES");
				if(one.equals(sysPara2.getParaValue())){
					ip = IpAddr.getV4IP();
				}else{
					ip = IpAddr.getCurrentIp().getHostAddress();
				}
			}*/
            if ("img".equals(im.getType())) {

                String port = String.valueOf(request.getServerPort());
//				String fileString="/"+"imAttach"+"/"+tee.getAttachFile().replace("\\", "/");
                File picture = new File(path);
                File thmpicture = new File(path);
                FileInputStream fis = new FileInputStream(picture);
                FileInputStream thmfis = new FileInputStream(thmpicture);
                //获取图片大小
                //  long size = fis.getChannel().size();
                //  long thmsize = thmfis.getChannel().size();
                BufferedImage sourceImg = ImageIO.read(fis);
                BufferedImage thmsourceImg = ImageIO.read(thmfis);
                file1.setFile_url(fileStr);
           /*      double size_k = size / 1024;
                BigDecimal l = new BigDecimal(Double.toString(size_k));
                double res = l.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                long ress = 0;
                if (size_k < 1024 && size_k > 0) {
                    if (Math.round(res) - res == 0) {
                        ress = (long) res;
                    }
                    file1.setFile_size(String.valueOf(ress) + "KB");
                } else if (size_k >= 1024) {
                    double size_m = size_k / 1024;
                    BigDecimal lm = new BigDecimal(Double.toString(size_k));
                    double res_m = l.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    long resss = 0;
                    if (Math.round(res_m) - res_m == 0) {
                        resss = (long) res_m;
                    }
                    file1.setFile_size(String.valueOf(resss) + "MB");
                }*/
                file1.setFile_size(size);
                file1.setFile_width(String.valueOf(sourceImg.getWidth()));
                file1.setFile_height(String.valueOf(sourceImg.getHeight()));
                file1.setThumbnail_url(fileStr);
                file1.setThumbnail_size(size);
              /*  if (size_k < 1024 && size_k > 0) {
                    if (Math.round(res) - res == 0) {
                        ress = (long) res;
                    }
                    file1.setThumbnail_size(String.valueOf(ress) + "KB");
                } else if (size_k >= 1024) {
                    double size_m = size_k / 1024;
                    BigDecimal lm = new BigDecimal(Double.toString(size_k));
                    double res_m = l.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    long resss = 0;
                    if (Math.round(res_m) - res_m == 0) {
                        resss = (long) res_m;
                    }
                    file1.setThumbnail_size(String.valueOf(resss) + "MB");
                }*/
                file1.setThumbnail_width(String.valueOf(thmsourceImg.getHeight()));
                file1.setThumbnail_height(String.valueOf(thmsourceImg.getWidth()));
            }
            //text   voice     img  file
            if ("voice".equals(im.getType())) {

                String port = String.valueOf(request.getServerPort());
                file1.setFile_url(fileStr);
                file1.setVoice_time(im.getThumbnailUrl());
            }
            //text file
            if ("file".equals(im.getType())) {


                String port = String.valueOf(request.getServerPort());
                file1.setFile_url(fileStr);
                file1.setFile_name(im.getFileName());
                file1.setFile_type(tee.getAttachName().substring(tee.getAttachName().lastIndexOf(".") + 1));
                file1.setFile_size(size);
        /*        File picture = new File(path);
                FileInputStream fis = new FileInputStream(picture);
                long size = fis.getChannel().size();
                double size_k = size / 1024;
                BigDecimal l = new BigDecimal(Double.toString(size_k));
                double res = l.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                long ress = 0;
                if (size_k < 1024 && size_k > 0) {
                    if (Math.round(res) - res == 0) {
                        ress = (long) res;
                    }
                    file1.setFile_size(String.valueOf(ress) + "KB");
                } else if (size_k >= 1024) {
                    double size_m = size_k / 1024;
                    BigDecimal lm = new BigDecimal(Double.toString(size_k));
                    double res_m = l.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    long resss = 0;
                    if (Math.round(res_m) - res_m == 0) {
                        resss = (long) res_m;
                    }
                    file1.setFile_size(String.valueOf(resss) + "MB");
                }*/
            }
        }


        ImMessageModel imm = new ImMessageModel(im.getFromUid()
                , im.getToUid()
                , im.getOfFrom()
                , im.getContent()
                , im.getOfTo()
                , im.getUuid()
                , im.getType()
                , file1
                , im.getStime());
        return imm;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-6-22 下午4:46:51
     * 方法介绍:   检索历史消息
     * 参数说明:   @param map
     * 参数说明:   @return
     *
     * @return List<ImMessageModel>
     * @throws IOException
     */
    public List<ImMessageModel> selectMessage(Map<String, Object> mapq) throws IOException {
        HttpServletRequest req = (HttpServletRequest) mapq.get("req");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("other_id1", mapq.get("other_id"));
        map.put("my_uid1", mapq.get("my_uid"));
        map.put("keyword1", mapq.get("keyword"));
        map.put("msg_type1", mapq.get("msg_type"));
        List<ImMessage> attMessageList = messageDao.selectMessage(map);
        List<ImMessageModel> messageList = new ArrayList<ImMessageModel>();
        for (ImMessage im : attMessageList) {
            ImMessageModel imm = this.getMessage(im, req);
            messageList.add(imm);
        }
        return messageList;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-6-22 下午5:42:12
     * 方法介绍:   开启或者关闭消息免打扰
     * 参数说明:   @param req
     * 参数说明:   @param list_id 列表id
     * 参数说明:   @param type  1:开启  0:关闭
     * 参数说明:   @param set_uid  当前用户uid
     * 参数说明:   @return
     *
     * @return Status
     */
    public Status updateMsgFree(Map<String, Object> map) {//String list_id,String type,String set_uid
        Status status = new Status();
        String list_id = (String) map.get("list_id");
        String type = (String) map.get("type");
        String set_uid = (String) map.get("set_uid");
        String uidSingle;
        Map<String, Object> para = new HashMap<String, Object>();
        para.put("list_id", list_id);
        ImChatData chat = chatDataDao.getSingleByListId(para);
        List<String> set_uids = new ArrayList<String>();
        if (chat != null && !StringUtils.checkNull(chat.getMsg_free())) {
            set_uids = Arrays.asList(chat.getMsg_free().split(","));
        } else if (chat != null) {
            chat.setMsg_free("");
        }
        if ("1".equals(type)) {
            if (!set_uids.contains(set_uid)) {
                String oldStr = chat.getMsg_free();
                if (StringUtils.checkNull(oldStr)) {
                    uidSingle = oldStr + set_uid + ",";
                } else {
                    uidSingle = set_uid + ",";
                }

                ImChatData chat1 = new ImChatData();
                chat1.setListId(list_id);
                chat1.setMsg_free(uidSingle);
                int result = chatDataDao.updateChatlist(chat1);
                if (result == 1) {
                    status.setStatus("ok");
                } else {
                    status.setStatus("error");
                }
            } else {
                status.setStatus("error");
            }
        }
        StringBuffer sb = null;
        if ("0".equals(type)) {
            if (set_uids.contains(set_uid)) {
                sb = new StringBuffer();
                int length = set_uids.size();
                for (int i = 0; i < length; i++) {
                    if (!set_uids.get(i).equals(set_uid)) {
                        sb.append(set_uids.get(i) + ",");
                    }
                }
                ImChatData chat0 = new ImChatData();
                chat0.setListId(list_id);
                chat0.setMsg_free(sb.toString());
                int result = chatDataDao.updateChatlist(chat0);
                if (result == 1) {
                    status.setStatus("ok");
                } else {
                    status.setStatus("error");
                }
            } else {
                status.setStatus("error");
            }
        }
        return status;
    }

    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017-6-26 上午11:.02:12
     * 方法介绍:   获取某个列表的权限
     * 参数说明:   @param req
     * 参数说明:   @param  of_from  当前用户的openfireid
     * 参数说明:   @param of_to  好友的openfireid或房间openfireid
     * 参数说明:   @param   msg_type 单聊:0 群聊:1
     * 参数说明:   @return
     */

    public ImMessageModel getPriv(String of_from, String of_to, String msg_type, HttpServletRequest request) {
        ImMessageModel messageModel = new ImMessageModel();
        messageModel.setMyStatus("false");
        messageModel.setList_id("");
        messageModel.setMsg_free("0");
        messageModel.setRinvite("0");
        String checkResult = StringUtils.checkNullUtils(
                new CheckCallBack() {
                    @Override
                    public boolean isNull(Object obj) {
                        // TODO Auto-generated method stub
                        if (obj instanceof String) {
                            String a = (String) obj;
                            if (a == null || "".equals(a)
                                    || a.length() == 0)
                                return true;
                        }
                        return false;
                    }
                }, of_from, "of_from不能为空", of_to, "of_to不能为空", msg_type,
                "msg_type不能为空");
        if (checkResult != null) {
            return messageModel;
        }
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("of_from", of_from);
        map.put("of_to", of_to);
        map.put("msg_type", msg_type);
        ImChatData priv = chatDataDao.queryListByCon(map);
        //判断是否为空
        if (priv != null) {
            messageModel.setList_id(priv.getListId());
            if (priv.getMsg_free() != null) {//免打扰
                List<String> uidArr = Arrays.asList(priv.getMsg_free().split(","));
                if (uidArr.contains(users.getUid().toString())) {
                    messageModel.setMsg_free("1");
                }
            }
            if ("1".equals(msg_type)) {//邀请
                Map<String, String> param = new HashMap<>();
                param.put("roomOf", of_to);
                ImRoom room = roomDao.getRoomByRoomOf(param);
                messageModel.setRinvite(room.getRinvite());
            }
            messageModel.setMyStatus("true");
        }
        return messageModel;
    }

    /**
     * 保存消息
     *
     * @param files
     * @param request
     * @param flag
     * @param from_uid
     * @param to_uid
     * @param of_from
     * @param of_to
     * @param content
     * @param type
     * @param time
     * @param uuid
     * @param msg_type
     * @param voice_time
     * @return
     */
    @Transactional(readOnly = false)
    public Object putMessageInfoPc(
            MultipartFile files[], HttpServletRequest request, final Integer flag, String from_uid,
            final String to_uid, String of_from, String of_to, final String content,
            final String type, String time, String uuid, final String msg_type, String voice_time
    ) {
        Status s = new Status();
        Files file1 = new Files();
        //全局变量记录在一个聊天中的最后一条信息 然后保存到ImChatData表中如果存在则修改
        String fileID = "";
        String attachName = "";
        String lastThumbnailUrl = "";
        //全局变量记录在一个聊天中的最后一条信息

        try {
            String checkResult = StringUtils.checkNullUtils(
                    new CheckCallBack() {
                        @Override
                        public boolean isNull(Object obj) {
                            // TODO Auto-generated method stub
                            if (obj instanceof String) {
                                String a = (String) obj;
                                if (a == null || "".equals(a)
                                        || a.length() == 0)
                                    return true;
                            }
                            if (obj instanceof Integer) {
                                Integer a = (Integer) obj;
                                if (a == null)
                                    return true;
                            }
                            return false;
                        }
                    }, flag, "flag不能为空", from_uid, "from_uid不能为空", to_uid,
                    "to_uid不能为空", of_from, "of_from不能为空", of_to, "of_to不能为空",
                    type, "type不能为空");
            if (checkResult != null) {
                s.setStatus("error");
                return s;
            }
            final List<Users> users = new ArrayList<Users>();
            if ("0".equals(msg_type)) {//单聊
                Users user = usersService.getByUid(Integer.parseInt(to_uid));
                if (user == null || user.getUid() == null) {
                    s.setStatus("nopeople");
                    return s;
                }
                Map<String, Object> paramss = new HashMap<String, Object>();
                paramss.put("fromUid", from_uid);
                paramss.put("toUid", to_uid);

                List<String> msgFrees = chatDataDao.getMsgFreeByUid(paramss);

                if (msgFrees != null && msgFrees.size() > 0) {
                    String msgFree = msgFrees.get(0);
                    String[] tempUids = msgFree.split(",");
                    if (tempUids != null && tempUids.length > 0) {
                        int count = 0;
                        for (String toUiddd : tempUids) {
                            if (to_uid.equals(toUiddd)) {
                                count++;
                                break;
                            }
                        }
                        if (count == 0) {
                            users.add(user);
                        }
                    }
                } else {
//                    System.out.println("0==||===========>消息打扰");
                    users.add(user);
                }

            } else {  //群聊
                Map<String, String> map = new HashMap<String, String>();
                map.put("roomOf", to_uid);
                ImRoom room = roomDao.getRoomByRoomOf(map);
                if ("-1".equals(room.getRoomStatus().toString())) {
                    s.setStatus("imerror-nogroup");
                    return s;
                }
                //排除群聊中设置免打扰的人员
                ImChatData imChatData = chatDataDao.getGroupByToUid(to_uid);
                List<Users> tempUser = new ArrayList<Users>();
                if (imChatData != null && !StringUtils.checkNull(imChatData.getMsg_free())) {
                    String[] tempUids = imChatData.getMsg_free().split(",");
                    tempUser = usersMapper.getUsersByUids(tempUids);
                }
                if (!StringUtils.checkNull(room.getRmemberUid())) {
                    String[] uids = room.getRmemberUid().split(",");
                    List<Users> userss = usersMapper.getUsersByUids(uids);
                    if (tempUser.size() > 0) {
                        for (Users u1 : userss) {
                            int count = 0;
                            for (Users u2 : tempUser) {
                                if (u1.getUid().equals(u2.getUid())) {
                                    count++;
                                    break;
                                }
                            }
                            if (count == 0) {
                                users.add(u1);
                            }
                        }
                    } else {
                        users.addAll(userss);
                    }

                } else {
                    s.setStatus("nopeople");
                    return s;
                }
            }

            ImMessage record = new ImMessage();
            record.setFromUid(from_uid);
            record.setType(type);
            record.setOfTo(of_to);
            record.setOfFrom(of_from);
            record.setToUid(to_uid);
            record.setUuid(uuid);
            //text   voice     img  file
            Attachment attach = null;
            switch (flag) {
                case 1:
                    //text
                    record.setContent(content);
                    break;
                case 3:

                    List<Attachment> attachs = attachService.upload(files, type, "im", "xoa" + (String) request.getSession().getAttribute("loginDateSouse"), false);
                    if (attachs == null) {
                        s.setStatus("error");
                        return s;
                    }
                    for (Attachment tee : attachs) {
                        record.setFileId(String.valueOf(tee.getAid()));
                        record.setFileName(tee.getYm());
                        //附件id
                        fileID = String.valueOf(tee.getAid());
                        //上传以后返回值交给ym
                        attachName = tee.getYm();
//				    String severpath=request.getRealPath("");
                        String fileString = tee.getUrl();
                        //图片处理
                        String path = tee.getPath();
                        //图片处理
                        if ("img".equals(type)) {
//					 String fileString="/"+"imAttach"+"/"+tee.getAttachFile().replace("\\", "/");
                            File picture = new File(fileString);
                            String deskFileName = UUID.randomUUID().toString() + ".png";
                            String deskUlr = path + System.getProperty("file.separator") + deskFileName;
                            FileUploadUtil.saveMinPhoto(fileString, deskUlr, 300, 1.0d);
                            File thmpicture = new File(deskUlr);

                            if (thmpicture.exists()) {
                                FileInputStream thmfis = new FileInputStream(thmpicture);
                                MultipartFile multipartFile = new MockMultipartFile(deskFileName, deskFileName, "img/txt", thmfis);
                                MultipartFile[] multipartFiles = new MultipartFile[]{multipartFile};
                                List<Attachment> attachss = attachService.upload(multipartFiles, type, "im", "xoa" + (String) request.getSession().getAttribute(
                                        "loginDateSouse"), true);
                                if (attachss != null && attachss.size() > 0) {
                                    Attachment themp = attachss.get(0);
                                    file1.setThumbnail_url(themp.getAttUrl());
                                    record.setThumbnailUrl(themp.getAttUrl());
                                    File thmpicture11 = new File(themp.getUrl());
                                    if (thmpicture11.exists()) {
                                        FileInputStream thmfiss = new FileInputStream(thmpicture11);
                                        BufferedImage thmsourceImgs = ImageIO.read(thmfiss);
                                        file1.setThumbnail_width(String.valueOf(thmsourceImgs.getHeight()));
                                        file1.setThumbnail_height(String.valueOf(thmsourceImgs.getWidth()));
                                    }
                                }
                                thmfis.close();
                            }
                            FileInputStream fis = new FileInputStream(picture);
                            //获取图片大小
                            long size = fis.getChannel().size();
                            BufferedImage sourceImg = ImageIO.read(fis);
                            //返回值file
                            file1.setFile_name(tee.getAttachName());
                            file1.setFile_url(tee.getAttUrl());
                            file1.setFile_size(this.reSize(tee.getSize()));
                            file1.setFile_type(tee.getAttachName().substring(tee.getAttachName().lastIndexOf(".") + 1));
                            file1.setFile_width(String.valueOf(sourceImg.getWidth()));
                            file1.setFile_height(String.valueOf(sourceImg.getHeight()));
                            fis.close();

                            //将附件信息保存起来
                            lastThumbnailUrl = tee.getAttUrl();
                            record.setRealUrl(tee.getAttUrl());
                        }
                        //voice   上传一条声音信息
                        if ("voice".equals(type)) {
//						 String fileString="/"+"imAttach"+"/"+tee.getAttachFile().replace("\\", "/");
                            //返回值file
                            file1.setFile_url(tee.getAttUrl());
                            file1.setVoice_time(voice_time);
                            //将附件信息保存起来
                            //将声音时间长度放入ThumbnailUrl 和 lastThumbnailUrl 用于记录时长  在app端处理  在获取时长返回时长时直接获取 可减缓服务器端压力
                            record.setThumbnailUrl(voice_time);
                            lastThumbnailUrl = voice_time;
                        }
                        //file 上传一个文档信息
                        if ("file".equals(type)) {
//						 String fileString="/"+"imAttach"+"/"+tee.getAttachFile().replace("\\", "/");
                            //返回值file
                            //  File picture = new File(fileString);
                            // FileInputStream fis = new FileInputStream(picture);
                            //long size = fis.getChannel().size();
                            file1.setFile_size(this.reSize(tee.getSize()));
//							double size_k=size/1024;
//							BigDecimal l=new BigDecimal(Double.toString(size_k));
//							double res=l.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
//							long ress=0;
//							if(size_k<1024&&size_k>0){
//								if(Math.round(res)-res==0){
//									ress=(long)res;
//								}
//								file1.setFile_size(String.valueOf(ress)+"KB");
//							}else if(size_k>=1024){
//								double size_m=size_k/1024;
//								BigDecimal lm=new BigDecimal(Double.toString(size_k));
//								double res_m=l.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
//								long resss=0;
//								if(Math.round(res_m)-res_m==0){
//									resss=(long)res_m;
//								}
//								file1.setFile_size(String.valueOf(resss)+"MB");
//							}else{
//								file1.setFile_size(String.valueOf(res)+"B");
//							}
                            file1.setFile_url(tee.getAttUrl());
                            file1.setFile_name(tee.getAttachName());
                            file1.setFile_type(tee.getAttachName().substring(tee.getAttachName().lastIndexOf(".") + 1));
                            record.setThumbnailUrl(tee.getAttUrl());
                            //将附件信息保存起来
                        }

                    }
                    break;
                default:
                    break;
            }
            record.setMsgType(msg_type);
            Long atime = new Date().getTime();
            record.setStime(String.valueOf(new Date().getTime()/1000));
            record.setAtime(String.valueOf(atime));
            int meResult = messageDao.save(record);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("fromUid", from_uid);
            map.put("toUid", to_uid);

            ImChatData chatModel = new ImChatData();
            chatModel.setFromUid(from_uid);
            chatModel.setToUid(to_uid);
            chatModel.setOfFrom(of_from);
            chatModel.setOfTo(of_to);
            chatModel.setLastTime(String.valueOf(atime/1000));
            chatModel.setLastAtime(String.valueOf(atime));
            if ("img".equals(type)) {
                //反之将内容置为空值
                chatModel.setLastContent("");

                chatModel.setLastFileId(fileID);
                chatModel.setLastFileName(attachName);
                chatModel.setLastThumbnailUrl(lastThumbnailUrl);
            } else if ("voice".equals(type)) {
                //反之将内容置为空值
                chatModel.setLastContent("");

                chatModel.setLastFileId(fileID);
                chatModel.setLastFileName(attachName);
                chatModel.setLastThumbnailUrl(lastThumbnailUrl);
            } else if ("file".equals(type)) {
                //反之将内容置为空值
                chatModel.setLastContent("");

                chatModel.setLastFileId(fileID);
                chatModel.setLastFileName(attachName);
                chatModel.setLastThumbnailUrl(lastThumbnailUrl);
            } else {
                chatModel.setLastContent(content);
                //如果最后一条信息为文字    上一条信息为附件 则将其他字段改为空值  在声明时已经初始化为空值
                chatModel.setLastFileId(fileID);
                chatModel.setLastFileName(attachName);
                chatModel.setLastThumbnailUrl(lastThumbnailUrl);
            }
            chatModel.setType(type);
            chatModel.setUuid(uuid);
            chatModel.setMsgType(msg_type);
            int chResult = 0;
            if ("1".equals(msg_type)) {//群聊，如果是往一个群里发送消息，存在这个群的记录，就进行更新，否则添加
                String listId = chatDataDao.getDatagroupObject(chatModel.getToUid());
                if (StringUtils.checkNull(listId)) {
                    chatModel.setUidIgnore("");
                    chResult = chatDataDao.saveChat(chatModel);
                } else {
                    chatModel.setListId(listId);
                    chatModel.setUidIgnore("");
                    chResult = chatDataDao.updateChatlist(chatModel);
                }
            } else {//单聊，只要存在两个人的对话直接进行更新，否则，进行插入
                int i = chatDataDao.getCountSingleObject(map);
                if (i == 0) {
                    chatModel.setUidIgnore("");
                    chResult = chatDataDao.saveChat(chatModel);
                } else {
                    List<String> listId = chatDataDao.getDataSingleObject(map);
                    chatModel.setListId(listId.get(0));
                    chatModel.setUidIgnore("");
                    chResult = chatDataDao.updateChatlist(chatModel);
                }
            }

            final String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
            final String jixiema = this.getMachineCode12();
            final Attachment finalAttach = attach;
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            final Users users1 = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
            this.threadPoolTaskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        String userName = users1.getUserName();
                        String con = users1.getUserName() + ":" + content;
                        if (!"0".equals(msg_type)) {
                            Map<String, Object> paramMap = new HashMap<String, Object>();
                            paramMap.put("uid", users1.getUid());
                            paramMap.put("roomOf", to_uid);
                            ImRoom room = roomDao.selRoomByRoomOfUid(paramMap);
                            userName = room.getRnamr();
                        }

                        if (flag == 3) {//文件 图片 定位
                            //String confile = "";
                            if ("img".equals(type)) {
                                con = users1.getUserName() + ":[图片]";
                            } else {
                                con = users1.getUserName() + ":[" + finalAttach.getAttachName() + "]";
                            }
                        }

                        //String[] acc = new String[users.size()];
                        //目标设备Token集合
                        com.alibaba.fastjson.JSONArray  deviceTokens = new com.alibaba.fastjson.JSONArray();
                        //极光推送list
                        List<String> jgList = new ArrayList<>();
                        for (int ssi = 0; ssi < users.size(); ssi++) {
                            //获取推送人的icqNo，即pushtoken
                            Users userAll = usersMapper.selectUserByUserId(users.get(ssi).getByname());
                            String token = userAll.getIcqNo();
                            if (StringUtils.checkNull(token)) {
                                String account = jixiema + users.get(ssi).getUserId() + sqlType;
                                jgList.add(account);
                            }else {
                                deviceTokens.add(token);
                            }

                        }
                        //极光推送数组(适配推送结构)
                        String[] jgArray = jgList.toArray(new String[jgList.size()]);

                       /* for (int ssi = 0; ssi < users.size(); ssi++) {
                            String account = jixiema + users.get(ssi).getUserId() + sqlType;
                            acc[ssi] = account;
                        }*/


                        //华为推送
                        sendPushMessage(userName,con,deviceTokens);
                        //极光推送通用版（ios+andriod）
                        JPushClient jpushClient = new JPushClient(JGSercetKey, JGKey, null, ClientConfig.getInstance());
                        PushPayload payload = buildPushObject_all_alias_alert(jgArray, userName, con);
                        PushResult result = jpushClient.sendPush(payload);

                        PushResult resultIos = null;
                        if (!JGKey.equals(JGIosStoreKey)) {
                            //极光推送ios商店版
                            JPushClient jpushClientios = new JPushClient(JGIosStoreSercetKey, JGIosStoreKey, null, ClientConfig.getInstance());
                            PushPayload payloadIos = buildPushObject_ios(jgArray, userName, con);;
                            resultIos = jpushClientios.sendPush(payloadIos);
                        }


          /*              if (!"200".equals(result.getResponseCode()) && !"200".equals(resultIos.getResponseCode())) {
                            //信鸽推送
                            Message mess = new Message();
                            MessageIOS messageIOS = new MessageIOS();
                            ClickAction clickAction = new ClickAction();
                            JSONObject contentTest = new JSONObject();
                            JSONObject obj = new JSONObject();
                            JSONObject aps = new JSONObject();
                            clickAction.setActionType(ClickAction.TYPE_ACTIVITY);
                            clickAction.setActivity("123");
                            Style style = new Style(0, 1, 1, 1, 0, 1, 0, 1);

                            mess.setType(Message.TYPE_NOTIFICATION);
                            mess.setStyle(style);
                            mess.setTitle(userName);
                            mess.setContent(con);
                            mess.setAction(clickAction);

                            contentTest.put("title", userName);//标题
                            contentTest.put("body", con);//内容
                            aps.put("badge_type", 1);
                            aps.put("alert", contentTest);
                            aps.put("sound", "beep.wav");
                            obj.put("aps", aps);
                            messageIOS.setRaw(obj.toString());

                            XingeApp pushIos = new XingeApp(Long.parseLong(iosKey), iosSercetKey);//IOS
                            XingeApp pushStore = new XingeApp(Long.parseLong(iosStopKey), iosStopSercetKey);//ios商业版
                            XingeApp pushAndroid = new XingeApp(Long.parseLong(androidKey), androidSercetKey);//安卓

                            for (Users user : users) {
                                if (!users1.getUserId().equals(user.getUserId())) {
                                    String account = jixiema + user.getUserId() + sqlType;

                                    JSONObject ret = pushAndroid.pushSingleAccount(0, account, mess);
                                    JSONObject ret3 = pushIos.pushSingleAccount(0, account, messageIOS, XingeApp.IOSENV_PROD);
                                    JSONObject ret4 = pushStore.pushSingleAccount(0, account, messageIOS, XingeApp.IOSENV_PROD);
                                }
                            }
                        }*/
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            if (chResult == 1 && meResult == 1) {
                s.setStatus("IMok");
            } else {
                s.setStatus("IMerror");
            }
            if (flag == 3) {
                file1.setStatus("ok");
                file1.setSendTime(String.valueOf(atime/1000));
                if ("0".equals(msg_type)) {
                    file1.setUserId(to_uid);
                } else {
                    file1.setRoomId(to_uid);
                }
                return file1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            s.setStatus("IMerror");
        }
        return s;


    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017-1-3 下午16:04:29
     * 方法介绍:   根据roomOf获取群人员
     *
     * @return
     */
    public ToJson<SimpleUser> getRoomPerson(HttpServletRequest request, String roomOf) {
        ToJson<SimpleUser> toJson = new ToJson<>(1, "error");
        try {
            List<SimpleUser> list = new ArrayList<>();
            Map<String, String> map = new HashMap<>();
            map.put("roomOf", roomOf);
            ImRoom imRoom = roomDao.getRoomByRoomOf(map);
            if (imRoom != null && !StringUtils.checkNull(imRoom.getRmemberUid())) {
                String[] arr = imRoom.getRmemberUid().split(",");
                list = usersMapper.selUserOrder(arr);
                String realPath = request.getSession().getServletContext().getRealPath("/");
                for (SimpleUser users : list) {
                    File file = new File(realPath + "ui/img/user/" + users.getAvatar());
                    if (!file.exists()) {
                        users.setAvatar(users.getSex());
                        users.setAvatar128(users.getSex());
                    }
                    if(users.getUid()==Integer.parseInt(imRoom.getRsetUid())){
                        users.setGroupOwner("1");
                    }
                }
            }
            toJson.setObj(list);
            toJson.setMsg("ok");
            toJson.setFlag(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toJson;
    }


    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017-12-26 下午1:56:29
     * 方法介绍:   删除列表消息
     *
     * @return
     */
    public ToJson<ImChatData> delChatList(HttpServletRequest request, int listId) {
        ToJson<ImChatData> toJson = new ToJson<>(1, "error");
        try {
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
            ImChatData chatData = chatDataDao.selChatByListId(listId);
            String uid = chatData.getUidIgnore() + user.getUid() + ",";
            Map<String, Object> map = new HashMap<>();
            map.put("listId", listId);
            map.put("uidIgnore", uid);
            int count = chatDataDao.upChatByIgnore(map);
            if (count > 0) {
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toJson;
    }

    public ToJson deleteByUUID(String uuid) {
        ToJson json = new ToJson();
        messageDao.updateDeleteFlagByUUID(uuid);
        json.setFlag(0);
        json.setMsg("ok");
        return json;
    }

    public BaseWrapper creatRoom(HttpServletRequest request, String companyId, Integer uid, String description, String natrueName, String members) {
        BaseWrapper wrapper = new BaseWrapper();
        AuthenticationToken authenticationToken = new AuthenticationToken(openfireAuthToken);
        RestApiClient restApiClient = new RestApiClient(openfireHost, Integer.parseInt(openfirePort), authenticationToken);
        //获取ofId
        String ofId = getOpenFireId(companyId, String.valueOf(uid));
        Users users = usersMapper.getByUid(uid);
        String ownerName = users.getUserName();
        String[] memberArr = new String[]{};
        if (!StringUtils.checkNull(members)) {
            memberArr = members.split(",");
        }
        List<Users> memberList = usersMapper.getUsersByUids(memberArr);
        Date now = new Date();
        String name = String.valueOf(now.getTime()).substring(0, 13);
        if (StringUtils.checkNull(natrueName)) { //实际的房间名称
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < memberList.size(); i++) {
                if (i > 2) {
                    sb.append("......");
                    break;
                }
                sb.append(memberList.get(i).getUserName());
                sb.append("、");
            }
            natrueName = ownerName + "、" + sb.toString();
        }
        if (StringUtils.checkNull(description)) { //实际的房间描述
            description = openfireDefaultDescription;
        }
        MUCRoomEntity chatRoom = new MUCRoomEntity(natrueName, name, description);
        chatRoom.setCreationDate(new Date());
        chatRoom.setPersistent(true);
        chatRoom.setPublicRoom(true);
        chatRoom.setRegistrationEnabled(true);
        chatRoom.setCanAnyoneDiscoverJID(false);
        chatRoom.setCanOccupantsChangeSubject(false);
        chatRoom.setCanOccupantsInvite(false);
        chatRoom.setCanChangeNickname(true);
        chatRoom.setMembersOnly(true);
        chatRoom.setModerated(true);
        chatRoom.setSubject(natrueName);
//        List<String> ofids=new ArrayList<String>();
//        ofids.add(ofId);
//        chatRoom.setOwners(ofids);
//        chatRoom.setAdmins(ofids);
        HashMap<String, String> param = new HashMap<String, String>();
        param.put("servicename", "gsrooms");
        Response response = restApiClient.createChatRoom(chatRoom, param);
        // Add user with role "owner" to a chat room
        restApiClient.addOwner(name, ofId, param);
        // Add user with role "admin" to a chat room
        restApiClient.addAdmin(name, ofId, param);
        // Add user with role "member" to a chat room
        restApiClient.addMember(name, ofId, param);
        for (String memberId : memberArr) {
            Response response1 = restApiClient.addMember(name, getOpenFireId(companyId, memberId), param);
        }
        Integer integer = response.getStatus();
        insertRoom(request, natrueName, String.valueOf(uid), ofId + "@gsubo", uid + "," + members, String.valueOf(now.getTime()), name + "@gsrooms.gsubo");
        if (integer.intValue() == 201) {
            wrapper.setFlag(true);
            wrapper.setMsg("成功");
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("roomOf", name + "@gsrooms.gsubo");
            resultMap.put("createtime", String.valueOf(now.getTime()));
            wrapper.setData(resultMap);
        } else {
            wrapper.setFlag(false);
            wrapper.setMsg("失败");
        }
        return wrapper;
    }

    private String getOpenFireId(String companyId, String uid) {
        return companyId + "pq" + uid;
    }

    public BaseWrapper updateRoom(HttpServletRequest request, Integer orderId,
                                  String notice,
                                  String introduce,
                                  String name,
                                  String roomOf,
                                  String members
            , Integer flag,String rsetUid) {
        BaseWrapper wrapper = new BaseWrapper();
        String oldMembers = "";
        if (flag != null && flag == 1) {
            oldMembers = members;
        } else {

            Map<String, String> param = new HashMap<String, String>();
            param.put("roomOf", roomOf);
            ImRoom oldRoom = roomDao.getRoomByRoomOf(param);

            Set<String> oldMemSet = new HashSet<String>();
            if (oldRoom != null) {
                oldMembers = oldRoom.getRmemberUid();
                String[] oldStrs = oldMembers.split(",");
                for (String old : oldStrs) {
                    oldMemSet.add(old);
                }
                if (oldMembers.endsWith(",")) {
                    oldMembers = oldMembers.substring(0, oldMembers.length() - 1);
                }
            }

            if (!StringUtils.checkNull(members)) {
                Boolean addFlag = false;
                StringBuilder content = new StringBuilder();
                String[] mems = members.split(",");
                for (String mem : mems) {
                    if (!oldMemSet.contains(mem)) {
                        oldMemSet.add(mem);
                        Users byUid = usersMapper.getByUid(Integer.parseInt(mem));
                        if (byUid != null && !StringUtils.checkNull(byUid.getUserName())) {
                            content.append(byUid.getUserName()).append("、");
                        }
                        addFlag = true;
                    }
                }

                // 判断是否增加了成员
                if (addFlag) {
                    String uuid = UUID.randomUUID().toString();
                    Users userByuid = usersMapper.findUserByuid(Integer.parseInt(oldRoom.getRsetUid()));
                    if (userByuid != null) {
                        content.deleteCharAt(content.length() - 1);
                        content.insert(0, userByuid.getUserName() + "邀请");
                        content.append("加入了本群。");
                    }
                    putMessageInfo(null, request, 1, oldRoom.getRsetUid(), oldRoom.getRoomOf(), oldRoom.getRsetOfid(), oldRoom.getRoomOf(), content.toString(), "text", String.valueOf(new Date().getTime() / 1000), uuid, "1", null, new Date().getTime());
                }

            }

            StringBuffer buffer = new StringBuffer();
            for (String aa : oldMemSet) {
                buffer.append(aa);
                buffer.append(",");
            }
            oldMembers = buffer.toString();
        }
        ImRoom irm = new ImRoom();
        irm.setRoomOf(roomOf);
        irm.setRmemberUid(oldMembers);
        irm.setRoomNo(orderId);
        irm.setRoomIntroduce(introduce);
        irm.setRoomRemark(notice);
        irm.setRnamr(name);
        if(!StringUtils.checkNull(rsetUid)){
            irm.setRsetUid(rsetUid);
        }
        roomDao.updateRoomMember(irm);
        wrapper.setFlag(true);
        wrapper.setMsg("操作成功");
        return wrapper;
    }

    public List<ImRoomModel> getAllRoomPc(String uid) {
        List<ImRoomModel> alist = new ArrayList<ImRoomModel>();
        Users u = usersMapper.getByUid(Integer.parseInt(uid));
        if (u == null) {
            return alist;
        }
        List<ImRoom> list = null;
        if (u.getUserPriv() == 1) {
            list = roomDao.getAllRoomByAdmin();
        } else {
            //获取登录人创建的群
            list = roomDao.getAllRoomWithCreater(u.getUid());
        }
        for (ImRoom ir : list) {
			/*String rNAME, String rOOM_OF, String rMEMBER_UID,
			String rOUT_UID, String rSET_UID, String rSET_OFID, String rTIME,
			String tYPE, String rCHANGE, String rINVITE*/
            String[] rmemberUid = ir.getRmemberUid().split(",");
            List<String> rmemberUidString = Arrays.asList(rmemberUid);
            ImRoomModel irm = new ImRoomModel(
                    ir.getRid(),
                    ir.getRnamr()
                    , ir.getRsetOfid()
                    , ir.getRmemberUid()
                    , ir.getRoutUid()
                    , ir.getRsetUid()
                    , ir.getRsetOfid()
                    , ir.getRtime()
                    , rmemberUidString.contains(u.getUid()) ? "1" : "0"
                    , ir.getRchange()
                    , ir.getRinvite()
                    , ir.getRoomOf(), ir.getRoomStatus(),
                    ir.getRoomNo()
                    , ir.getRoomRemark(), ir.getRoomIntroduce());
            alist.add(irm);
        }
        for (ImRoomModel imRoomModel : alist) {
            String rmember_uid = imRoomModel.getRmember_uid();
            String rset_uid = imRoomModel.getRset_uid();
            if (rmember_uid != null && rmember_uid.endsWith(",")) {
                rmember_uid = rmember_uid.substring(0, rmember_uid.length() - 1);
            }
            if (rset_uid != null && rset_uid.endsWith(",")) {
                rset_uid = rset_uid.substring(0, rset_uid.length() - 1);
            }
            try {
                String name = usersService.findUsersByuidReturn(rmember_uid);
                String name1 = usersService.findUsersByuidReturn(rset_uid);
                imRoomModel.setRmemberUidName(name);
                imRoomModel.setRsetUidName(name1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return alist;

    }


    public String reSize(String attamentSize) {
        //获取对应附件或图片声音的大小
        String size = "";
        if (!StringUtils.checkNull(attamentSize)) {
            size = attamentSize;
            if (size.contains("MB")) {
                //size.replace("MB"," ");
                size = String.valueOf(Double.parseDouble(size.substring(0, size.length() - 2).trim()) * 1024);
            } else if (size.contains("KB")) {
                //size.replace("KB"," ");
                size = size.substring(0, size.length() - 2).trim();
            } else {
                //size.replace("B"," ");
                //size = String.valueOf(Integer.parseInt(size.trim())/1000);
                double temp = Double.parseDouble(size.substring(0, size.length() - 1).trim()) / 1024;
                ;
                temp = temp > 0.01 ? (double) Math.round(temp * 100) / 100 : 0.01;
                size = String.valueOf(temp);
            }
        } else {
            size = "0";
        }
        return size;
    }

    public static PushPayload buildPushObject_ios(String[] account, String alert, String message) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.alias(account))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(IosAlert.newBuilder()
                                        .setTitleAndBody(alert, "", message)
                                        .setActionLocKey("PLAY")
                                        .build())
                                .setBadge(1)
                                .setSound("happy")
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();
    }


    public static PushPayload buildPushObject_all_alias_alert(String[] account, String alert, String message) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(account))
                // .setNotification(Notification.alert(alert))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(alert)
                                .setTitle(message)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(IosAlert.newBuilder()
                                        .setTitleAndBody(alert, "",message )
                                        .setActionLocKey("PLAY")
                                        .build())
                                .setBadge(1)
                                .setSound("happy")
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();
    }
    /**
     * 华为推送
     */

    /**获取下发通知消息的认证Token*/

    //获取下发通知消息的认证Token
    private static  void refreshToken() throws IOException
    {
        String msgBody = MessageFormat.format(
                "grant_type=client_credentials&client_secret={0}&client_id={1}",
                URLEncoder.encode(appSecret, "UTF-8"), appId);
        String response = httpPost(tokenUrl, msgBody, 5000, 5000);
        com.alibaba.fastjson.JSONObject obj = com.alibaba.fastjson.JSONObject.parseObject(response);
        accessToken = obj.getString("access_token");
        tokenExpiredTime = System.currentTimeMillis() + obj.getLong("expires_in") - 5*60*1000;
    }


    //发送Push消息
    public void sendPushMessage(String userName,String con,com.alibaba.fastjson.JSONArray  deviceTokens) {
//        ToJson<SmsBody> json = new ToJson<SmsBody>();
        try {
            /**判断是否过期如果过期则重新获取token*/
            if (tokenExpiredTime <= System.currentTimeMillis()) {
                refreshToken();
            }

            /**发信息*/
            //仅通知栏消息需要设置标题和内容，透传消息key和value为用户自定义
            com.alibaba.fastjson.JSONObject body = new com.alibaba.fastjson.JSONObject();
            body.put("title", userName);//发信人
            body.put("content", con);//消息内容体

            /**
             * 消息点击动作参数
             */
            com.alibaba.fastjson.JSONObject param = new com.alibaba.fastjson.JSONObject();
            param.put("appPkgName", "com.huawei.hms.hmsdemo");//定义需要打开的appPkgName

            /**
             * 消息点击动作
             * 定义消息的点击动作，type=1时为自定义动作，即intent。Type= 3为默认动作，打开app。
             */
            com.alibaba.fastjson.JSONObject action = new com.alibaba.fastjson.JSONObject();
            action.put("type", 3);
            action.put("param", param);//消息点击动作参数

            /**
             * push消息定义
             */
            com.alibaba.fastjson.JSONObject msg = new com.alibaba.fastjson.JSONObject();
            msg.put("type", 3);//3: 通知栏消息，异步透传消息请根据接口文档设置
            msg.put("action", action);//消息点击动作
            msg.put("body", body);//通知栏消息body内容

            /**
             * 扩展信息，含BI消息统计，特定展示风格，消息折叠。
             */
            com.alibaba.fastjson.JSONObject ext = new com.alibaba.fastjson.JSONObject();
            //设置消息标签，如果带了这个标签，会在回执中推送给CP用于检测某种类型消息的到达率和状态
            ext.put("biTag", "Trump");
            //自定义推送消息在通知栏的图标,value为一个公网可以访问的URL
            ext.put("icon", "http://8oa.cn/assets/main_img/huawei.jpg");

            /**
             * 华为push消息总结构体
             */
            com.alibaba.fastjson.JSONObject hps = new com.alibaba.fastjson.JSONObject();//华为PUSH消息总结构体
            hps.put("msg", msg);
            hps.put("ext", ext);

            /**
             * 放进总体结构，最高父级hps
             */
            com.alibaba.fastjson.JSONObject payload = new com.alibaba.fastjson.JSONObject();
            payload.put("hps", hps);

            /**
             * 请求发送接口
             */
            String postBody = MessageFormat.format(
                    "access_token={0}&nsp_svc={1}&nsp_ts={2}&device_token_list={3}&payload={4}",
                    URLEncoder.encode(accessToken,"UTF-8"),
                    URLEncoder.encode("openpush.message.api.send","UTF-8"),
                    URLEncoder.encode(String.valueOf(System.currentTimeMillis() / 1000),"UTF-8"),
                    URLEncoder.encode(deviceTokens.toString(),"UTF-8"),
                    URLEncoder.encode(payload.toString(),"UTF-8"));

            String postUrl = apiUrl + "?nsp_ctx=" + URLEncoder.encode("{\"ver\":\"1\", \"appId\":\"" + appId + "\"}", "UTF-8");
            httpPost(postUrl, postBody, 5000, 5000);
        }catch (Exception e) {
            e.printStackTrace();

        }
    }


    /**
     * 推送
     * @param httpUrl
     * @param data
     * @param connectTimeout
     * @param readTimeout
     * @return
     * @throws IOException
     */
    public static String httpPost(String httpUrl, String data, int connectTimeout, int readTimeout) throws IOException
    {
        OutputStream outPut = null;
        HttpURLConnection urlConnection = null;
        InputStream in = null;

        try
        {
            URL url = new URL(httpUrl);
            urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            urlConnection.setConnectTimeout(connectTimeout);
            urlConnection.setReadTimeout(readTimeout);
            urlConnection.connect();

            // POST data
            outPut = urlConnection.getOutputStream();
            outPut.write(data.getBytes("UTF-8"));
            outPut.flush();

            // read response
            if (urlConnection.getResponseCode() < 400)
            {
                in = urlConnection.getInputStream();
            }
            else
            {
                in = urlConnection.getErrorStream();
            }

            List<String> lines = IOUtils.readLines(in, urlConnection.getContentEncoding());
            StringBuffer strBuf = new StringBuffer();
            for (String line : lines)
            {
                strBuf.append(line);
            }
           // System.out.println(strBuf.toString());
            return strBuf.toString();
        }
        finally
        {
            IOUtils.closeQuietly(outPut);
            IOUtils.closeQuietly(in);
            if (urlConnection != null)
            {
                urlConnection.disconnect();
            }
        }
    }


    public void  testNotificationMessageSend(List<String> tokens, String title, String body) throws HuaweiMesssagingException {
        HuaweiCredential credential = HuaweiCredential.builder()
                .setAppId(AppIdKey)
                .setAppSecret(appSecret)
                .build();

        HuaweiOption option = HuaweiOption.builder()
                .setCredential(credential)
                .build();
        HuaweiApp app = HuaweiApp.initializeApp(option);

        //String token = "1004103023061481981059500600CN01";
        com.huawei.push.javasdk.message.Notification notification = new com.huawei.push.javasdk.message.Notification(title, body);
        com.huawei.push.javasdk.message.ClickAction clickAction = ClickAction.builder()
                .setType(1)
                .setIntent("#Intent;compo=com.rvr/.Activity;S.W=U;end")
                .build();
        com.huawei.push.javasdk.message.AndroidNotification androidNotification = com.huawei.push.javasdk.message.AndroidNotification.builder()
                .setTitle(title)
                .setBody(body)
                .setClickAction(clickAction).setIcon("http://8oa.cn/assets/main_img/huawei.jpg")
                .build();

        AndroidConfig androidConfig = AndroidConfig.builder()
                .setNotification(androidNotification)
                .build();

        com.huawei.push.javasdk.message.Message message = com.huawei.push.javasdk.message.Message.builder()
                .setNotification(notification)
                .setAndroidConfig(androidConfig)
                .addAllToken(tokens)
                .build();

        SendResponce responce = HuaweiMessaging.getInstance(app).send(message, false);
        app.clearInstancesForTest();
        Assert.assertEquals("Success", responce.getMsg());
    }

    public void testNotificationMessageSend(String tokens, String title, String body,Integer total) throws HuaweiMesssagingException {
        HuaweiCredential credential = HuaweiCredential.builder()
                .setAppId(AppIdKey)
                .setAppSecret(SecretKey)
                .build();

        HuaweiOption option = HuaweiOption.builder()
                .setCredential(credential)
                .build();
        HuaweiApp app = HuaweiApp.initializeApp(option);

        //String token = "1004103023061481981059500600CN01";
        com.huawei.push.javasdk.message.Notification notification = new com.huawei.push.javasdk.message.Notification(title, body);
        com.huawei.push.javasdk.message.ClickAction clickAction = ClickAction.builder()
                .setType(1)
                .setIntent("#Intent;compo=com.rvr/.Activity;S.W=U;end")
                .build();
        com.huawei.push.javasdk.message.AndroidNotification androidNotification = com.huawei.push.javasdk.message.AndroidNotification.builder()
                .setTitle(title)
                .setBody(body)
                .setClickAction(clickAction).setIcon("http://8oa.cn/assets/main_img/huawei.jpg")
                .setBadge(new BadgeNotification(total,Huawei_badge_class))
                .build();

        AndroidConfig androidConfig = AndroidConfig.builder()
                .setNotification(androidNotification)
                .build();

        com.huawei.push.javasdk.message.Message message = com.huawei.push.javasdk.message.Message.builder()
                .setNotification(notification)
                .setAndroidConfig(androidConfig)
                .addToken(tokens)
                .build();

        SendResponce responce = HuaweiMessaging.getInstance(app).send(message, false);
        //app.clearInstancesForTest();
        Assert.assertEquals("Success", responce.getMsg());
    }

    public String getMachineCode12() {
        String machineCode = null;
        try {
            SysPara para = sysParaMapper.querySysPara("PUSH_MNO");
            if (para != null && !StringUtils.checkNull(para.getParaValue())) {
                machineCode = para.getParaValue().substring(0, 12);
            } else {
                machineCode = MachineCode.get16CharMacs() == null ? "" : MachineCode.get16CharMacs().get(0);
            }
        } catch (Exception e) {
        }
        return machineCode;
    }

    public static String FormetFileSize(long fileS) {//转换文件大小
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if(fileS==0){
            return "0.00B";
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }
}

